Having a static list/seq of users with 10K records, is this threadsafe?

Viewed 31

Say I have a static reference to a list/seq of a collection of users:

val users = List(User(..), User(...))

In my controllers, depending on the querystring filters passed in I will filter the users collection.

/users/find?locationId=1&age=30

The action would look something like:

def findUsers(...) = Action {
  val filteredUsers = users.filter(.....)
  Ok(filteredUsers)
}

So if this endpoint is getting 10K requests per second, the fact that the users reference is a val and I a am simply filtering the results in a read-only manner, this endpoint should be blazing fast correct?

The second part to this question is, since I cannot hard code 10K users in a collection, what would be the best way to mimic this behaviour or am I forced to make this a var in this case if I load the data from a db?

var users = userService.getAll()

I would need to reload this users periodically, like maybe every 3-4 hours.

1 Answers

So if this endpoint is getting 10K requests per second, the fact that the users reference is a val and I a am simply filtering the results in a read-only manner, this endpoint should be blazing fast correct?

Yes, no concerns with thread safety here. If you use something that refreshes this list you might get varying responses if 2 clients hit the same url when cache is being refreshed. It's possible to remediate this if that's an issue. In most cases it's not a problem.

You could use a var if you want to implement refresh yourself. There are other ways like using an actor which will hold this state. However, the best option I think is already provided by Play framework: ScalaCache

https://www.playframework.com/documentation/2.8.x/ScalaCache

It has cache refresh and expiry.

If you want further speedups you can cache results of your filtering if it makes sense for you. So it could be double cache for all results and filtered results or just for filtered results. Depends on your needs.

Related