KatInterview

Courier Earnings Report from a Paginated Payments Feed

SQL & DataModel answer
MediumModel answerSQL & Datapythondata-aggregationpagination

Last 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:

  1. The implementation, with per-courier totals and itemized output.
  2. A set of test cases covering the edge cases above.
  3. 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.