Prevent Duplicate Request Using Idempotency

Tri Wicaksono
Ralali Tech Stories
3 min readDec 4, 2020

What is Idempotency?

Idempotency is a way to handle the same request more than once, but the receiving service will only perform one operation.

How does it Work?

Things that need to be considered in the implementation of Idempotency.

Common Scenario in REST API

In REST API, we frequently found the situation when you experienced the request timeout, the client will usually retry the request. The problem will occur if it is not handled properly such as:

  • Multiple operations
  • Error
  • etc.

So, Idempotency is created to solve that problem.

What is REST?

REST (Representational State Transfer) is a web-based communication architecture standard that is often applied in web-based service development. Generally using HTTP (Hypertext Transfer Protocol) as a protocol for data communication. REST was first introduced by Roy Fielding in 2000.

In the REST architecture, the REST server provides resources or data and the REST client can access and display these resources for future use. Each resource is identified by a URI (Universal Resource Identifier) or a global ID. Resources are represented in text format, JSON or XML. In general, the format uses JSON and XML.

The Advantages of REST

  • Agnostic language and platform
  • More simple to develop than SOAP
  • Easy to learn, doesn’t depend of any tools
  • Compact, doesn’t require additional messaging layer
  • Closer to the web by design and philosophically

The Disadvantages of REST

  • Assumes a point-to-point communication model — Cannot be used for distributed computing environments where messages will pass through one or more intermediaries
  • Lack of standard support for security, policies, message reliability, etc., so services that has sophisticated requirements are more difficult to develop (self-solved)
  • Relates to the HTTP transport model
  • Unique Identifier (Unique ID) can be in the form of Reference ID, Transaction ID, Inquiry ID
  • Check it First then Execute Logic approach Before executing the main logic, it is necessary for us to check it first whether the Unique ID already exists or not in the system.
  • If found, we can return the current data
  • If not found, we can execute the main logic (e.g. create record)

Sample Pseudo Code

The Benefits of Implementing Idempotency

  • Avoid duplicated operations when client do some retry
  • In some cases, it can prevent the other service dependency from overload because it already being held in CheckExist

--

--