Arnol
Arnol

Reputation: 2147

How to share result between multiple concurrent requests in Elixir/Phoenix?

I have a working API service written in Elixir using Phoenix. It has the following endpoint:

  1. Receive a string parameter.
  2. Check if result already exists in cache (DB or file, the parameter is cache key):
    • If yes, return result immediately.
    • If no, perform an external request to a third-party service, process the request response, cache the result and then return it.

It is working fine. But now I want to share result between concurrent requests: if there's a request A is waiting for third-party service response or processing result, other requests with the same parameter should not do the same job, they should wait for the result from request A.

I would really appreciate if anyone can help me finding a solution for this.

Upvotes: 0

Views: 474

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Simply wrap the function calling 3rd party service into GenServer.handle_call/3.

This process implementing GenServer behaviour would be maintaining queue for free; OTP will do.

The subsequent request would be put into the process mailbox until this one is completed, so all the following requests would hit a cache.

Upvotes: 2

Related Questions