Design an API Billing and Usage System with Free Quotas
Company: Zapier
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Other
Design an API billing and usage system that tracks API calls made by users and computes charges based on tiered pricing plans.
Each user is registered under a plan that defines a free quota (the number of calls included at no cost) and a per-call cost in cents for any usage beyond the quota. The system logs every API call with a timestamp and lets clients query a user's total usage and current bill.
All bills are returned in cents as integers to avoid floating-point precision issues. When querying usage within a time window, the range is **inclusive** on both ends.
Implement the following methods:
- `registerUser(userId: int, freeQuota: int, costPerCall: int)`: Register a user with the given free quota and per-call cost in cents. Overwrites any existing registration.
- `logCall(userId: int, timestamp: int)`: Record an API call made by the user at the given timestamp. Timestamps are non-decreasing across calls for the same user.
- `getUsage(userId: int, start: int, end: int) -> int`: Return the number of API calls made by the user within the inclusive time window `[start, end]`. Returns 0 if the user is not registered.
- `getBill(userId: int) -> int`: Return the user's current bill in cents, `max(0, totalCalls - freeQuota) * costPerCall`. Returns 0 if the user is not registered.
Example 1:
```text
Input:
["ApiBillingSystem", "registerUser", "logCall", "logCall", "logCall", "getUsage", "getBill"]
[[], [1, 2, 5], [1, 100], [1, 200], [1, 300], [1, 100, 300], [1]]
Output: [null, null, null, null, null, 3, 5]
```
```python
billing = ApiBillingSystem() # empty system
billing.registerUser(1, 2, 5) # user 1: 2 free calls, then 5 cents per call
billing.logCall(1, 100) # calls: [100]
billing.logCall(1, 200) # calls: [100, 200]
billing.logCall(1, 300) # calls: [100, 200, 300]
billing.getUsage(1, 100, 300) # 3: all three calls are in the window
billing.getBill(1) # 5: 3 - 2 = 1 billable call at 5 cents
```
Example 2:
```text
Input:
["ApiBillingSystem", "registerUser", "logCall", "logCall", "logCall", "getUsage", "getUsage", "getBill", "registerUser", "getBill", "getUsage", "getBill"]
[[], [7, 0, 3], [7, 10], [7, 10], [7, 25], [7, 10, 24], [7, 11, 25], [7], [7, 5, 3], [7], [8, 0, 100], [8]]
Output: [null, null, null, null, null, 2, 1, 9, null, 0, 0, 0]
```
User 7 has no free calls and pays 3 cents per call. Two calls share timestamp 10, so the window [10, 24] counts 2 and the window [11, 25] counts only the call at 25. The bill is 3 billable calls times 3 cents, or 9. Re-registering user 7 with a free quota of 5 keeps the three logged calls, and all three now fit inside the quota, so the bill drops to 0. User 8 never registered, so both queries return 0.
```hint Use the ordering guarantee
Each user's timestamps arrive already sorted. Counting the entries of a sorted list that fall inside a range does not require a scan.
```
### Constraints & Assumptions
- `1 <= userId <= 10⁶`
- `0 <= freeQuota <= 10⁶`
- `0 <= costPerCall <= 10⁴` (cents)
- `0 <= timestamp <= 10⁹`
- Timestamps passed to `logCall` for the same user are non-decreasing.
- `start <= end` in any `getUsage` query.
- At most `10⁵` total operations.
- Re-registering a user replaces the plan and keeps the call history. `getBill` applies the current plan to every logged call.
### Clarifying Questions to Ask
- What should `logCall` do for a user who has not registered: record the call, drop it, or raise an error?
- Can calls for one user ever arrive out of timestamp order, for example from retries or from several servers?
- Will the methods be called from several threads at once?
- Must every timestamp be kept forever, or can old calls be rolled up into counts?
### What a Strong Answer Covers
- The per-user state the system keeps and why appending preserves sorted order.
- An inclusive window count in logarithmic time, with correct handling of calls exactly at `start` or `end` and of repeated timestamps.
- Integer-cent billing with the clamp at zero, and the size of the largest possible bill.
- The rules for unregistered users and for re-registration, applied consistently across all four methods.
- Time and space complexity of each method.
### Follow-up Questions
- How would you price graduated tiers, for example the first 1,000 billable calls at one rate and every call after that at a lower rate?
- If calls can arrive out of order, what structure would you use for the log, and what would each method cost?
- How would you add monthly billing periods in which the free quota resets?
- At billions of calls, how would you cut memory while still answering window queries?
Overview: Design an API billing and usage tracker that logs timestamped calls per user, counts calls in an inclusive time window, and bills usage beyond a free quota in integer cents. It tests per-user state design, binary search over a sorted log, and careful rules for unregistered users and re-registration.