Courier Earnings Report from a Paginated Payments Feed
SQL & DataModel answerLast updated
Aggregate per-courier earnings for a pay period from a paginated, time-zoned event feed, handling corrections, cancellations, and rounding, with itemized totals.
You are building the earnings report for a delivery platform's couriers. A REST endpoint, GET /payout, returns a stream of pay-related events for individual deliveries. Each event describes one component of the money attached to a delivery and carries a timestamp. Components include base pay, distance and time bonuses, promotions, tips, fees, adjustments, taxes, refunds, and chargebacks.
Write a Python or SQL solution that computes, for each courier, the total pay for a given pay period, together with an itemized per-component breakdown.
Your solution should cope with the following real-world complications:
- Pagination: results arrive in pages, and pages may overlap, be empty, or fail transiently.
- Late or missing events: corrections for an earlier event can arrive afterwards, and some fields may be absent.
- Time zones: timestamps can be in UTC, carry an explicit offset, or be naive. The pay period is defined in local calendar dates of the market, including partial days at the boundaries and daylight-saving transitions.
- Cancellations and chargebacks: a cancelled delivery changes what is payable, and clawbacks can refer to work paid in an earlier period.
- Negative adjustments: these reduce earnings, and the net for a courier can even be negative.
- Rounding: money must be exact, and the itemized breakdown must reconcile with the total.
State any assumptions you make about the payload format, sign conventions, and cancellation semantics before you code them. Then provide:
- The implementation, with per-courier totals and itemized output.
- A set of test cases covering the edge cases above.
- A discussion of time and space complexity, and how you would scale it up.
Hints
Hint 1
Treat it as a pipeline: fetch all pages, validate, deduplicate, normalize timestamps, filter to the period, apply cancellation rules, aggregate, then round once at the end.
Hint 2
Use exact decimal arithmetic parsed from strings, and make the period a half-open interval [local start of first day, local start of the day after the last day) converted to UTC so DST days and midnight events are handled correctly.
Hint 3
Deduplicate by event id keeping the highest version so replays and overlapping pages do not change the answer, and define the total as the signed sum of the already-rounded component totals so the breakdown always reconciles.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract first
Before coding, state your assumptions explicitly. This is what I would assume:
- Response shape:
GET /payout?cursor=...returns{"data": [...], "next_cursor": string | null}. - Event fields:
event_id,version,dasher_id(courier),delivery_id,component,amount(decimal string),currency,event_time(ISO-8601), and an optionalstatuswhere"void"marks a tombstone. - Signs: earnings (base, distance bonus, time bonus, promotion, tip) are positive. Deductions (fee, tax, refund, chargeback) arrive as positive magnitudes and are subtracted.
adjustmentis already signed. - Period: inclusive local dates in the market's time zone, interpreted as the half-open interval
[start 00:00, end+1 00:00). - Cancellation: a
cancellationevent voids the base, bonus, and promotion components of that delivery within the period. The tip survives unless separately refunded. Clawbacks for earlier-period work come aschargebackevents dated in the current period. - Corrections: re-sent with a higher
version. We keep the max version perevent_id. - Rounding: sum exact decimals per component, round each component half-up to cents once, and define total as the signed sum of the rounded components.
Approach
The solution is a single pipeline:
- Fetch pages until the cursor is null. Retry transient errors with exponential backoff and detect repeated cursors to avoid infinite loops.
- Validate each record: required fields present, known component, supported currency, parsable amount and timestamp. Rejects go into an audit list with a reason, never silently dropped.
- Deduplicate by
event_id, keeping the highestversion. Drop tombstones. This makes the result independent of page overlap and arrival order. - Normalize time: parse timestamps, attach the market zone to naive ones, convert to UTC. Compute UTC bounds from local midnight so 23-hour and 25-hour DST days work automatically.
- Filter to events in
[lo, hi). - Apply cancellations: collect the set of cancelled
(dasher, delivery)pairs, then skip voidable components for them. - Aggregate exact
Decimalamounts intocourier -> component -> amount. - Round each component once with
ROUND_HALF_UP, then compute the total from the rounded parts.
Why this is correct
- Exact money:
Decimalparsed from strings avoids float drift such as0.1 + 0.2 != 0.3. - Idempotence: dedupe by
(event_id, max version)means replays, overlapping pages, and late corrections give the same answer. - Unambiguous boundaries: a half-open interval puts an event at exactly local midnight in exactly one period.
- Reconciliation: rounding per component once and deriving the total from the rounded parts guarantees the statement adds up. Rounding per event accumulates error: three events of 0.335 round to 0.34 each (total 1.02), while the exact sum 1.005 rounds to 1.01.
Implementation sketch
from collections import defaultdict
from datetime import datetime, date, time as dtime, timedelta, timezone
from decimal import Decimal, ROUND_HALF_UP, InvalidOperation
from zoneinfo import ZoneInfo
EARN = {"base_pay", "distance_bonus", "time_bonus", "promotion", "tip"}
DEDUCT = {"fee", "tax", "refund", "chargeback"}
VOIDABLE = {"base_pay", "distance_bonus", "time_bonus", "promotion"}
KNOWN = EARN | DEDUCT | {"adjustment", "cancellation"}
CENT = Decimal("0.01")
def parse_ts(s, tz):
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
return (dt if dt.tzinfo else dt.replace(tzinfo=tz)).astimezone(timezone.utc)
def compute(events, start: date, end: date, tz_name="America/Los_Angeles"):
tz = ZoneInfo(tz_name)
lo = datetime.combine(start, dtime.min, tz).astimezone(timezone.utc)
hi = datetime.combine(end + timedelta(days=1), dtime.min, tz).astimezone(timezone.utc)
latest, rejects = {}, []
for e in events:
try:
if e["component"] not in KNOWN or e.get("currency", "USD") != "USD":
raise ValueError("unsupported")
rec = {**e, "amt": Decimal(str(e["amount"])),
"ts": parse_ts(e["event_time"], tz),
"ver": int(e.get("version", 0))}
except (KeyError, ValueError, InvalidOperation) as err:
rejects.append((e, str(err))); continue
p = latest.get(rec["event_id"])
if p is None or rec["ver"] > p["ver"]:
latest[rec["event_id"]] = rec
live = [r for r in latest.values()
if r.get("status") != "void" and lo <= r["ts"] < hi]
cancelled = {(r["dasher_id"], r["delivery_id"])
for r in live if r["component"] == "cancellation"}
agg = defaultdict(lambda: defaultdict(Decimal))
for r in live:
c = r["component"]
if c == "cancellation":
continue
if c in VOIDABLE and (r["dasher_id"], r.get("delivery_id")) in cancelled:
continue
agg[r["dasher_id"]][c] += r["amt"]
out = {}
for d, comps in agg.items():
rounded = {c: v.quantize(CENT, ROUND_HALF_UP) for c, v in comps.items()}
total = sum((v if c in EARN or c == "adjustment" else -v)
for c, v in rounded.items())
out[d] = {"items": rounded, "total": total, "negative": total < 0}
return out, rejects
Complexity
With N events, P pages, D couriers, C components:
- Time: O(N) for the passes, plus P network calls, which usually dominate wall-clock time.
- Space: O(N) for the dedupe map and O(D x C) for aggregates.
- At scale: push the dedupe and aggregation into SQL (
ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY version DESC), filter onrn = 1, thenGROUP BY dasher_id, component) or Spark, or stream pages into a keyed store.
Tests to include
- Overlapping pages containing the same event twice, and a repeated cursor (expect a clear error).
- A correction with a higher version replacing the original amount, and a tombstone removing an event.
- An event at exactly local midnight on the start and end boundaries (belongs to one period only).
- A DST spring-forward and fall-back day inside the period.
- Naive,
Z, and explicit-offset timestamps. - A cancelled delivery with a tip (tip kept) and a chargeback with no matching delivery in the period.
- A negative adjustment pushing a courier's net below zero (reported as negative and flagged, not clamped).
- Half-cent rounding such as
0.005 -> 0.01, and a breakdown that sums exactly to the total. - Malformed records (missing field, unknown component, non-USD) landing in the rejects list.
Common mistakes
- Using floats for money.
- Rounding per event instead of per component after summing.
- Using an inclusive end timestamp, or comparing local times to UTC without conversion.
- Assuming pages never overlap, or looping forever on a bad cursor.
- Clamping negative totals to zero and hiding a real debt.
- Silently dropping malformed events instead of auditing them.