Sessionize API Requests per Key With a 30-Minute Inactivity Gap

Last updated: November 29, 2026

Quick Overview

Given a log of API requests with api_key_id, org_id, and timestamp, assign requests to sessions where a new session starts after more than 30 minutes of inactivity for that key. Then report per org the number of sessions, average requests per session, average session length, and how many sessions had a single request.

OpenAI
Data Manipulation (SQL/Python)
Data Scientist
OpenAI
November 29, 2026
Data Scientist
Onsite
Data Manipulation (SQL/Python)
Medium

0

0

0 solved


Given a log of API requests with api_key_id, org_id, and timestamp, assign requests to sessions where a new session starts after more than 30 minutes of inactivity for that key. Then report per org the number of sessions, average requests per session, average session length, and how many sessions had a single request.

OpenAI's platform team studies how developers use the API: bursty batch jobs, steady production traffic, or one-off experiments. Sessionization with window functions is a classic SQL exercise, and the interviewer watches for the gaps and islands pattern and precise boundary handling.

What the Interviewer Expects
  • Uses LAG partitioned by key and ordered by time
  • Flags session starts and turns them into ids with a running SUM
  • States clearly whether a gap of exactly 30 minutes starts a new session
  • Aggregates to sessions before aggregating to orgs
  • Avoids floating point error in time differences
Key Topics to Cover
window functions
sessionization
gaps and islands
LAG
running sums
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 sessionize when the same key is used by several unrelated services?
  • How would you do this incrementally on a daily partitioned table where sessions cross midnight?
  • How would you choose the 30 minute threshold from the data?
  • How would you write this in pandas?
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
  • api_requests(api_key_id, org_id, request_ts); a key belongs to one org.
  • Session boundary: gap strictly greater than 30 minutes starts a new session; exactly 30 continues it.
  • Session length = l...
Approach

Gaps and islands: compare each request to the previous one for the same key with LAG. Mark is_new = 1 when there is no previous request or the gap exceeds 1800 seconds. A running SUM(is_new) per...


Submit Your Answer
Markdown supported