Video in progress

How do you reliably enforce a limit like "at most 5 SMS per user per day" with only the database when several instances are running?

"Count first, then write" breaks the limit under parallel requests. The reliable way is an atomic counter on a (user_id, day) row: INSERT ... ON CONFLICT DO UPDATE SET cnt = cnt + 1 WHERE cnt < 5 RETURNING cnt. If no row comes back, the limit is used up.

📖 Answer

The naive code:

long sent = repo.countToday(userId);
if (sent >= 5) throw new LimitExceeded();
smsRepo.save(new Sms(userId, text));

Three instances see count = 4 at the same time and all three send: 7 SMS.

An atomic counter:

CREATE TABLE sms_quota (
    user_id bigint,
    day     date,
    cnt     int NOT NULL,
    PRIMARY KEY (user_id, day)
);

INSERT INTO sms_quota AS q (user_id, day, cnt)
VALUES (:userId, current_date, 1)
ON CONFLICT (user_id, day)
DO UPDATE SET cnt = q.cnt + 1
WHERE q.cnt < 5
RETURNING cnt;

ON CONFLICT DO UPDATE takes the row lock, so parallel calls go through one at a time and the WHERE is checked against the fresh value each time. When the limit is reached, the UPDATE doesn't run and RETURNING returns nothing.

Subtle points:

  • incrementing the quota and sending the SMS should be in one transaction, or the quota must be returned if the SMS fails, depending on the business decision;
  • current_date depends on the server's time zone: if the "day" should be by Tashkent time, I compute the date in the application and pass it in;
  • clean up old rows regularly (or use daily partitions).

If the limit is very hot (thousands per second on a single key), that row becomes a hot spot, and an atomic INCR + TTL in Redis fits better. But for money or legal limits, I still keep the database as the source of truth.