0

I have an app written in java and using mysql as DB. I need to create a coupon distributed system where I have 100 coupons stored in DB and the first 100 customers who login should get those coupons. With a single server its pretty straight forward I think, but how do I implement this where my application server has multiple load balanced instances with the login service? To be more specific my problem is that at a given time 1000s of users may be trying to login, so how do I maintain FIFO order?

1 Answer 1

2

There are two ways to approach requirements like this:

  • Try to find a real distributed solution, which will involve distributed transactions and nontrivial patterns like two-phase commit or the saga pattern.

  • Solve the distribution in a centralized manner, by providing a single, dedicated service running on one isolated instance which does the accounting.

The second approach does not stop the main part of the system still working in a distributed fashion. For a small number like 100 coupons, I would definitely prefer it, since the isolated service is unlikely to become a bottleneck.

If I had several millions of coupons to distribute, or the distribution of each coupon creates a lot of heavy load, then I would start to think about the first approach. Note the first approach might need to implement a centralized service as well, but extended this design by some mechanics which distributes batches of coupons to the login service instances, return them back when they were not requested within a certain time frame, or some other complex distribution algorithm.

Note in a distributed system, each of the load balanced instances of the login service might have each own clock with slight differences in what the current time is. So if one tries to use those different clocks to decide what "First In" means, this will necessarily end up in collisions. A central service is probably the easiest way resolve this.

2
  • How would saga help with procuring the coupon from DB? In a single instance service I can use something like semaphores to procure a coupon from db. What kind of transaction would a saga pattern make?
    – dev Joshi
    Commented Jan 25, 2023 at 12:27
  • @devJoshi: with a single instance service, you may implement a semaphore on your own, or you use a transactional DB in the service which already solves the concurrency issues. I mentioned the Saga pattern as a general approach for solving comparable distributed transactional requirements, it may not necessarily be required here.
    – Doc Brown
    Commented Jan 25, 2023 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.