Quota & Rate-Limit System for a Mobile AI App
System DesignModel answerLast updated
Design the client-server quota enforcement system for a mobile AI assistant, covering API contract, Android architecture, and multi-device synchronization.
Context
You are a mobile engineer at a company shipping an AI chat app on Android. The app offers multiple model tiers: a free tier capped at 10 requests per day, and a premium tier capped at 40 requests per 3-hour rolling window for the flagship model. When users approach or hit their cap, the app must respond gracefully — showing remaining message counts, a live countdown to the next reset, and prompts to either wait or upgrade — all without adding any latency to message dispatch.
What You Need to Design
Functional Expectations
- Users can always see how many messages they have left and when their quota refills.
- The send button disables (or redirects to a fallback model) the moment the cap is reached.
- Mid-stream quota exhaustion, back-to-back rapid sends, and usage from another device are all handled cleanly.
- The server is the authoritative source of truth, but the UI feels instant.
Non-Functional Expectations
- Quota enforcement must add zero client-side round trips before a message is sent.
- The system should tolerate device clock drift and brief network outages.
- Target scale: 50 million daily active users, peak 100,000 requests per second.
What to Address
- API contract and sync strategy — how quota data travels between server and client (headers, SSE events, polling, etc.) and how reset timestamps are communicated and interpreted.
- Android architecture — the state machine, persistence layer, and reactive data flow that keep multiple UI components (composer, model picker, banners) in sync.
- Concurrency and edge cases — race conditions from rapid taps, speculative UI updates that need to be rolled back on a 429, clock skew between device and server, and multi-device desynchronization.
Describe your end-to-end design with concrete API shapes, data structures, and code where it helps clarify the approach.
Hints
Hint 1
Resist the urge to add a dedicated polling loop for quota status. Every response the server already sends is an opportunity to piggyback fresh quota data — use that instead, and reserve a dedicated quota endpoint only for cold-start or foreground resume.
Hint 2
Absolute epoch timestamps from the server are safer than relative offsets (e.g., 'resets in 3600 seconds'), but they only solve half the clock problem. A device with a wrong wall clock will still mis-render a countdown. Anchoring to the monotonic clock using the server-client time delta is what fully eliminates drift.
Hint 3
Keep a single application-scoped repository as the sole writer of quota state, and derive all UI representations from one shared StateFlow. This prevents the composer, the model picker, and the banner from independently managing quota and getting out of step with each other.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope Before Designing
Two quota semantics are in play here and they behave differently under load:
- Rolling window (premium: 40 per 3 hours): each message expires exactly 3 hours after it was sent, so the available count rises continuously as old messages age out.
- Fixed window (free: 10 per day): the entire count resets at a fixed UTC boundary. Simpler server logic but creates burst patterns right after reset.
Both share one important rule: a message counts when the server accepts it and begins generation — not on submit, and not if the network fails before any tokens are produced. This is the definition that determines when to charge and when to refund.
Scale sanity check: 100k RPS × 2 Redis operations per request (reserve + charge/release) = 200k ops/s. A sharded Redis cluster of 10–20 primaries handles this comfortably. A rolling-window log stores at most 40 timestamps per user per active model — roughly 400 bytes. At 20M concurrent active users that is about 8 GB, well within a standard deployment.
2. API Contract: Piggyback on the Chat Stream
The most important design decision is to never add a round trip. Quota state travels as response headers on the chat request itself, plus a terminal SSE event at the close of the stream.
POST /v1/conversations/{id}/messages
Idempotency-Key: <uuid>
→ 200 text/event-stream
X-Quota-Limit: 40
X-Quota-Remaining: 12
X-Quota-Reset-At: 1735689600000 // epoch ms, server clock
X-Server-Time: 1735680000000
...token delta events...
event: quota
data: {"remaining":12,"reset_at":1735689600000,"charged":true}
event: done
Headers give the UI the post-reservation state at the first byte of the response, so the composer can update immediately. The terminal quota event carries the final authoritative value — useful because a concurrent device could consume quota mid-stream, or a cancel could trigger a refund.
On quota exhaustion the server returns:
HTTP 429
{
"code": "quota_exceeded",
"remaining": 0,
"reset_at": 1735689600000,
"server_time": 1735680000000,
"fallback_model": "gpt-mini"
}
The fallback_model field lets the client silently offer a downgrade instead of a hard block, which is a significant UX improvement for premium users who run out mid-conversation.
A dedicated GET /v1/quota endpoint exists but is called only on app cold start, foreground resume after a gap, login, and tier change. Never on a timer.
3. Server Enforcement
Each user-model pair gets a Redis sorted set keyed quota:{userId}:{modelId}, where members are reservation IDs scored by accepted-at timestamp (epoch ms).
A Lua script handles the atomic reserve in a single round trip:
- Trim all members scored older than
now - windowMs. - If
ZCARD >= limit, return 429 withreset_at = lowestScore + windowMs. - Otherwise
ZADDthe new reservation ID and return updatedremainingandreset_at.
Reservations move through three states — RESERVED → CHARGED → RELEASED — with a 10-minute TTL as a safety net. The Idempotency-Key maps 1:1 to a reservation ID, so a retried POST never double-charges.
If Redis is unavailable: fail open for paid tiers using a short local token bucket in the gateway, fail closed for free tiers where abuse risk is higher. All charges write asynchronously to a durable store for billing reconciliation.
4. Android Architecture
A single application-scoped QuotaRepository (Hilt @Singleton) is the only writer of quota state. Every screen — composer, model picker, upgrade banner — reads from it. This eliminates the fragmentation that happens when components manage their own quota copies.
sealed interface QuotaState {
data object Unknown : QuotaState
data class Available(val remaining: Int, val limit: Int, val resetAtServer: Long) : QuotaState
data class Exhausted(val resetAtServer: Long, val fallback: ModelId?) : QuotaState
}
@Singleton
class QuotaRepository @Inject constructor(
private val store: QuotaStore, // DataStore for lightweight persistence
private val clock: ServerClock, // holds computed server-client offset
@AppScope private val scope: CoroutineScope
) {
private val _state = MutableStateFlow>(emptyMap())
val state: StateFlow> = _state.asStateFlow()
private val mutex = Mutex()
private val pending = mutableMapOf<String, ModelId>() // idempotencyKey → model
// Optimistic decrement before the request leaves the device
suspend fun tryReserve(model: ModelId, key: String): Boolean = mutex.withLock {
val s = _state.value[model]
if (s is QuotaState.Exhausted && clock.nowServer() < s.resetAtServer) return false
if (s is QuotaState.Available) {
val next = if (s.remaining <= 1) QuotaState.Exhausted(s.resetAtServer, null)
else s.copy(remaining = s.remaining - 1)
_state.update { it + (model to next) }
}
pending[key] = model
true
}
// Server response always wins — apply and persist
suspend fun applyServer(model: ModelId, snap: QuotaSnapshot, key: String?) = mutex.withLock {
key?.let(pending::remove)
clock.sync(snap.serverTime)
_state.update { it + (model to snap.toState()) }
store.save(model, snap)
}
// Undo the optimistic decrement on network error (not on 429)
suspend fun rollback(model: ModelId, key: String) = mutex.withLock {
if (pending.remove(key) == null) return@withLock
_state.update { cur -> cur + (model to cur[model].incremented()) }
}
}
Clock skew. The repository computes offset = serverTime - System.currentTimeMillis() from every server response. Countdowns anchor to the monotonic clock: deadlineElapsed = SystemClock.elapsedRealtime() + (resetAt - serverTime). This makes timers immune to the user manually changing their device clock. After a reboot, elapsedRealtime resets, so the countdown recomputes from the persisted resetAt and the current offset.
Countdown flow. A derived Flow ticks once per second when under 60 seconds remain, and once per minute otherwise. It uses stateIn(WhileSubscribed(5000)) so it stops ticking when no UI is observing it. When it reaches zero, the state flips to Unknown and fires one GET /v1/quota to confirm the reset.
ViewModel UX state. The ChatViewModel combines quotaRepo.state with composer state into a single UiState that carries sendEnabled, a banner variant (Low / Exhausted with countdown / Upgrade), and an optional modelOverride for the fallback downgrade flow.
5. Key Edge Cases
Rapid taps. The Mutex plus the optimistic decrement mean the second tap sees the already-decremented count synchronously. The button also disables while a send is in-flight. The server still enforces atomically: two simultaneous requests racing for the last slot get one 200 and one 429.
429 rollback. On a 429, do not restore the optimistic decrement — apply the server snapshot as-is. The user's message text stays in the composer, flagged as unsent, so they can act on it when quota refills.
Mid-stream exhaustion. If a quota event arrives during a stream with charged: false, stop rendering further tokens and surface the exhausted state in place. Partial responses are discarded, not shown.
Multi-device sync. Another device spending quota mid-stream is reconciled by the terminal quota event. The client never trusts its own running count across sessions; the server's word at stream close is final.
Common Mistakes to Avoid
- Polling for quota status — adds unnecessary load and latency; piggyback on existing responses instead.
- Trusting only device timestamps — always anchor countdowns to server time plus monotonic elapsed to survive clock drift and user time changes.
- Multiple quota state owners — if the composer, banner, and model picker each maintain their own state, they will disagree. One repository, one
StateFlow. - Charging on submit — charge only when the server begins generation, so cancels and network failures before first token are automatically free.