Handling Concurrent Requests in a RESTful API

Guillaume Viguier-Just
The Startup
Published in
5 min readSep 23, 2020

--

Imagine the following scenario:

  1. User A requests resource 1 via a GET endpoint
  2. User B requests resource 1 via a GET endpoint
  3. User A makes changes on resource 1 and saves its changes via a PUT request
  4. User B makes changes on resource 1, on the same fields as user A, and saves its changes via a PUT request

Since users A and B both requested the same version of resource 1, you now have a problem, because the PUT request triggered by user B erased the changes made by user A, and chances are, user A is mad and wondering why his changes do not show up anymore, even though he swears that he did not forget to save. Does that scenario sound familiar? If so, read on.

Identifying the problem

The problem is very simple: users A and B requested a resource more or less at the same time, and got the same version of this resource. Then, they both made changes to the resource in parallel, and whoever saved last erased the changes of the other.

There are actually 2 possible ways to solve this issue: through what’s called pessimistic locking or optimistic locking.

Pessimistic vs Optimistic locking

Pessimistic locking means that as soon as a user starts making changes on a resource, he locks this resource. While this resource is locked, no one else can edit this resource. When the user is…

--

--

Guillaume Viguier-Just
The Startup

Développeur web et passionné de finances personnelles