Rolling Seven-Day Token Spend per Org With Spike Detection

Last updated: November 29, 2026

Quick Overview

From raw usage events with org_id, timestamp, and input and output token counts, compute each org's daily tokens, a rolling 7-day total, and flag days where usage exceeds three times the average of the prior seven days, with days of no usage counted as zero.

OpenAI
Data Manipulation (SQL/Python)
Data Engineer
OpenAI
November 29, 2026
Data Engineer
Onsite
Data Manipulation (SQL/Python)
Hard

0

0

0 solved


From raw usage events with org_id, timestamp, and input and output token counts, compute each org's daily tokens, a rolling 7-day total, and flag days where usage exceeds three times the average of the prior seven days, with days of no usage counted as zero.

OpenAI's billing and trust teams watch for sudden usage spikes, which can mean a leaked API key, a runaway agent loop, or a customer launch that needs capacity. The interviewer is testing time series SQL: filling missing days, ROWS versus RANGE frames, excluding the current day from the baseline, and avoiding noisy alerts.

What the Interviewer Expects
  • Aggregates events to daily totals before windowing
  • Builds a date spine so missing days count as zero
  • Uses a frame that excludes the current day for the baseline
  • Requires a full baseline window before flagging
  • Adds an absolute volume floor to suppress noise from tiny orgs
Key Topics to Cover
window functions
time series
date spine
anomaly detection
rolling aggregates
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you make the detector robust to weekly seasonality?
  • Would a median or a z-score baseline work better, and how would you compute it in SQL?
  • How would you run this hourly at scale on a warehouse?
  • How would you alert on a likely leaked key versus a legitimate launch?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data
  • usage_events(org_id, ts, input_tokens, output_tokens), many rows per day.
  • calendar(day): one row per date (a standard dimension table; otherwise a recursive CTE).
  • Spike: today's tokens > 3 t...
Approach

Windows over raw rows with ROWS BETWEEN 6 PRECEDING would mean six events, not six days, and windows over daily rows with gaps would stretch across missing dates. So: aggregate to daily, cross each ...


Submit Your Answer
Markdown supported