Full answer
text
rate_counts(user_id, window_start, count, PRIMARY KEY (user_id, window_start))
INSERT INTO rate_counts (user_id, window_start, count)
VALUES (:u, date_trunc('minute', now()), 1)
ON CONFLICT (user_id, window_start) DO UPDATE SET count = rate_counts.count + 1
RETURNING count;If the returned count is above 100, reject with HTTP 429. Old windows are deleted by a periodic job.
Trade-offs:
- Fixed windows allow up to 200 requests across a minute boundary. A sliding window (weighting the previous minute's count) or a token bucket smooths this.
- Every request is a write, and a busy user's row becomes a hot row.
- In-memory stores with atomic increments and expiry suit this better at scale, with the database kept for long-term quotas such as monthly limits.
The upsert pattern itself is the same as in other counter items in this bank and was not run here with date_trunc.
Key points
- Upsert a counter per user and window
- Reject when the count passes the limit
- Fixed windows allow edge bursts
- Every request writes
- In-memory stores suit high traffic
Common mistakes
- Counting rows in a request log on every call
- Never cleaning up old windows
Follow-ups
- How does a token bucket work?
- How would you enforce a monthly quota?
Tips
- Mention the boundary burst