Camera Log Ingestion and Query API Server
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build an in-memory HTTP routing and storage service, CameraLogServer, that sits between networked security cameras uploading structured event batches and client applications querying those logs.
Rather than opening network sockets in unit tests, requests enter through a single method:
handle(method: str, path: str, body: Optional[Union[str, bytes]] = None) -> Tuple[int, Dict[str, Any]]
Every call returns (status_code, response_dict). All error responses must return a JSON-serializable dictionary containing an "error" string describing the problem. Because real web servers dispatch concurrent requests across worker threads, CameraLogServer must be thread-safe.
Endpoints and Behavior
-
Ingest a batch —
POST /cameras/{camera_id}/logs- The request
body(stror UTF-8bytes) must parse as a JSON object{"entries": [...]}containing between1and1000log entry objects:"id": non-emptystr, unique within thatcamera_id."timestamp": non-negativeintrepresenting epoch milliseconds (boolandfloatvalues are invalid)."severity":str, one of"DEBUG","INFO","WARN", or"ERROR", ordered"DEBUG" < "INFO" < "WARN" < "ERROR"."message":str.
- Batch validation: If
camera_idis invalid,bodyis missing or malformed JSON,"entries"is missing, not a list, or empty, returns400. If"entries"contains more than1000items, returns413. If any element in"entries"fails field validation, reject the entire request with400without storing partial entries or registering an unknown camera. - Idempotent deduplication: A camera becomes registered on its first valid upload. Any entry whose
"id"was already stored for thatcamera_id(including an"id"repeated earlier in the same batch) is skipped rather than duplicated. Return{"camera_id": camera_id, "stored": <new_count>, "duplicates": <skipped_count>}with status201whenstored > 0, or status200whenstored == 0.
- The request
-
Query stored logs —
GET /cameras/{camera_id}/logs- Supports optional query parameters:
start,end: ASCII base-10 integers filtering the half-open timestamp intervalstart <= timestamp < end(each bound is optional;start > endreturns400).min_severity: minimum severity threshold to include (default"DEBUG").order:"asc"(oldest first, default) or"desc"(newest first). Entries sharing the exact sametimestampkeep their original arrival order under"asc"and reverse arrival order under"desc".limit: integer page size in1..1000(default100).cursor: the"next_cursor"string returned by the preceding page for the same query filters. Pagination must visit matching entries without gaps or duplicates even if new logs are inserted between page fetches.
- Reject invalid
camera_idvalues, unrecognized parameter names, duplicate parameter keys (such as?limit=5&limit=10), blank values (?limit=), non-standard integer strings (whitespace, underscores, non-ASCII digits), or invalid cursors with400. - If
camera_idhas never completed a valid upload, return404. - Otherwise return
200with{"camera_id": camera_id, "entries": [...], "next_cursor": <str or None>}, setting"next_cursor"toNonewhen no further matching entries exist.
- Supports optional query parameters:
-
List registered cameras —
GET /cameras- Return
200with{"cameras": [...]}containing all registeredcamera_idstrings in ascending lexicographical order.
- Return
-
Path and method errors
camera_idmust match^[A-Za-z0-9_-]{1,64}$after splitting the URL path on"/"and percent-decoding each non-empty segment (otherwise400).- Return
404for any unrecognized route, and405when a valid route is called with an unsupported HTTP method.
Examples
Example 1
Input:
1. POST /cameras/lobby-north/logs
body: {"entries": [
{"id": "ev-9", "timestamp": 1500, "severity": "INFO", "message": "stream steady"},
{"id": "ev-2", "timestamp": 1100, "severity": "ERROR", "message": "lens obstructed"},
{"id": "ev-5", "timestamp": 1300, "severity": "WARN", "message": "bitrate drop"}
]}
2. POST /cameras/lobby-north/logs (identical body retried)
3. GET /cameras/lobby-north/logs?start=1100&end=1500&min_severity=WARN
4. GET /cameras
Output:
1. (201, {"camera_id": "lobby-north", "stored": 3, "duplicates": 0})
2. (200, {"camera_id": "lobby-north", "stored": 0, "duplicates": 3})
3. (200, {
"camera_id": "lobby-north",
"entries": [
{"id": "ev-2", "timestamp": 1100, "severity": "ERROR", "message": "lens obstructed"},
{"id": "ev-5", "timestamp": 1300, "severity": "WARN", "message": "bitrate drop"}
],
"next_cursor": None
})
4. (200, {"cameras": ["lobby-north"]})
Explanation: The first upload stores all three out-of-order entries (201) and registers "lobby-north". Retrying the identical batch skips all three known IDs and responds with 200. Querying [1100, 1500) excludes timestamp 1500 because end is exclusive, filters to WARN and ERROR, and returns the matches ordered by timestamp.
Example 2
Input:
1. POST /cameras/dock-west/logs
body: {"entries": [
{"id": "m1", "timestamp": 5000, "severity": "DEBUG", "message": "heartbeat"},
{"id": "m2", "timestamp": 5000, "severity": "INFO", "message": "motion start"},
{"id": "m3", "timestamp": 5200, "severity": "INFO", "message": "motion end"}
]}
2. GET /cameras/dock-west/logs?limit=2
3. GET /cameras/dock-west/logs?limit=2&cursor=<next_cursor_from_step_2>
4. GET /cameras/unknown-cam/logs
5. DELETE /cameras/dock-west/logs
Output:
1. (201, {"camera_id": "dock-west", "stored": 3, "duplicates": 0})
2. (200, {"camera_id": "dock-west", "entries": [m1, m2], "next_cursor": "<opaque_token>"})
3. (200, {"camera_id": "dock-west", "entries": [m3], "next_cursor": None})
4. (404, {"error": "..."})
5. (405, {"error": "..."})
Explanation: m1 and m2 share timestamp 5000, so "asc" preserves their arrival order on the first 2-item page and emits a cursor token. Passing that cursor retrieves the remaining item m3 with "next_cursor": None. Reading an unregistered camera returns 404, and DELETE on the logs route returns 405.
Constraints
camera_idconsists of1to64characters fromA-Z,a-z,0-9,_, and-.1 <= len(entries) <= 1000per validPOST(0entries returns400;> 1000entries returns413).timestampis an integer withtimestamp >= 0(boolandfloatare rejected).1 <= limit <= 1000(default100).- Entry
"id"uniqueness is scoped percamera_id; two different cameras may reuse the same entry"id". - In-memory persistence for the lifetime of the
CameraLogServerinstance is sufficient, and concurrenthandle(...)calls across multiple threads must remain race-free.
Step-by-step walkthrough
Review the API contract and core invariants
Before writing handler code, summarize the HTTP contract and invariants our service must uphold across uploads, queries, and error responses:
[Cameras] [API Server] [Clients] lobby-north, --- POST /cameras/{id}/logs ---> Validate + Deduplicate <--- GET /cameras/{id}/logs --- dock-west (JSON batch of entries) Per-camera sorted store (time window, severity, protected by Lock order, cursor paging)Here are the concrete design pillars behind each endpoint:
- Entry schema & batch uploads: Each entry carries
id(unique string per camera),timestamp(non-negative integer milliseconds since the Unix epoch),severity(DEBUG<INFO<WARN<ERROR), andmessage(string). Cameras upload batches (1..1000entries perPOST) to amortize HTTP overhead; a batch above1000returns413. - Safe retries (idempotency): If a network timeout causes a device to resend a batch, entries whose
idis already in that camera'sseen_idsset are skipped rather than duplicated. Storing at least one new entry returns201; a pure retry wherestored == 0returns200. - Unknown cameras vs empty results: A camera becomes registered on its first valid upload. Querying a camera that has never uploaded returns
404, cleanly distinguishing a typo incamera_id(404) from a registered camera with zero matching logs in a window (200with"entries": []). - Time-range, severity, ordering, and pagination:
GET /cameras/{camera_id}/logsfilters by half-open[start, end)(start <= timestamp < end, so adjacent windows[1000, 1500)and[1500, 2000)never double-count timestamp1500),min_severity,order("asc"or"desc"),limit(1..1000, default100), andcursor. - Camera directory & routing errors:
GET /cameraslists registered camera IDs in sorted order; unrecognized paths return404and unsupported HTTP methods return405.
Endpoint & Method Success Errors --------------------------------------- ------------------------------ -------------------------------------- POST /cameras/{camera_id}/logs 201 (new) / 200 (all dupes) 400 bad JSON/field, 413 >1000 entries GET /cameras/{camera_id}/logs?... 200 {entries, next_cursor} 400 bad/unknown param, 404 unknown cam GET /cameras 200 {cameras: [sorted ids]} 405 on non-GET Any other path / wrong HTTP method — 404 unknown path, 405 wrong method- Entry schema & batch uploads: Each entry carries
Separate core routing from the HTTP socket adapter
Testing a server over real TCP sockets is slow and flaky. Putting the entire HTTP contract inside one pure method—
handle(method, path, body) -> (status_code, response_dict)—lets tests callhandledirectly in microseconds while keeping the real socket adapter (ThreadingHTTPServeror Flask) thin.Three routing details prevent subtle bugs:
- Raise
BadRequeston validation failures: CatchingBadRequestonce inhandle()turns any bad input into400 {"error": ...}without cluttering every helper withif err: return 400. - Split on
"/"before URL-decoding (unquote): That way, a percent-encoded slash inside a camera ID (/cameras/bad%2Fid/logs) stays insidesegments[1] == "bad/id"and gets rejected as an invalidcamera_id(400) instead of looking like an extra URL segment. - Pass
keep_blank_values=Truetoparse_qs: By default,parse_qs("limit=")silently drops blank keys ({}), which would treat?limit=as "use default 100" instead of rejecting the malformed blank integer with400.
from urllib.parse import parse_qs, unquote, urlsplit class BadRequest(Exception): """Raised whenever request validation fails; handle() converts it into HTTP 400.""" class CameraLogServer: def handle(self, method, path, body=None): try: return self._route(method, path, body) except BadRequest as exc: return 400, {"error": str(exc)} def _route(self, method, path, body): url = urlsplit(path) # Split on "/" before unquoting so an encoded "%2F" stays inside one segment and fails check_camera_id. segments = [] for part in url.path.split("/"): if part: segments.append(unquote(part)) # keep_blank_values=True retains empty parameters like "?limit=" so int_param rejects them with 400. query = parse_qs(url.query, keep_blank_values=True) if segments == ["cameras"]: if method != "GET": return 405, {"error": "method not allowed", "allowed": ["GET"]} return self._list_cameras() if len(segments) == 3 and segments[0] == "cameras" and segments[2] == "logs": camera_id = segments[1] if method == "POST": return self._upload(camera_id, body) if method == "GET": return self._read(camera_id, query) return 405, {"error": "method not allowed", "allowed": ["GET", "POST"]} return 404, {"error": "no such endpoint"}- Raise
Validate uploads all-or-nothing and parse query parameters strictly
Camera firmware and human query URLs can send malformed types, so we validate strictly:
- All-or-nothing batches: We validate every item in
entriesbefore touching storage. Ifentries[7]is malformed,entries[0..6]are not stored and a rejected batch never registers a phantom camera. - Python's
booland unhashable traps:isinstance(True, int)isTruein Python, soparse_entryrejectsboolexplicitly ontimestamp. Similarly, checkingisinstance(severity, str)beforeseverity in SEVERITY_RANKprevents["INFO"] in SEVERITY_RANKfrom crashing withTypeError: unhashable type: 'list'. - Strict query parameters: Unknown parameter names (such as a typo
?severity=ERRORinstead of?min_severity=ERROR), duplicate parameters (?start=1&start=2), and non-ASCII/underscored integers (limit=1_0orstart=%201, which Python'sint()would quietly accept!) all fail with400.
import json import re SEVERITY_RANK = {"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3} CAMERA_ID = re.compile(r"[A-Za-z0-9_-]{1,64}") INTEGER = re.compile(r"-?[0-9]+") def check_camera_id(camera_id): """Ensure camera_id has 1..64 safe URL characters.""" if not CAMERA_ID.fullmatch(camera_id): raise BadRequest("camera_id must be 1-64 characters from A-Z a-z 0-9 _ -") def parse_json_body(body): """Decode a str or bytes request body as JSON, raising BadRequest on empty or invalid input.""" if body is None or len(body) == 0: raise BadRequest("a JSON request body is required") try: return json.loads(body) except ValueError: # Both json.JSONDecodeError and UnicodeDecodeError inherit from ValueError. raise BadRequest("the request body is not valid JSON") def parse_entry(item, index): """Validate one uploaded log object and return a normalized dict.""" where = f"entries[{index}]" if not isinstance(item, dict): raise BadRequest(f"{where} must be an object") entry_id = item.get("id") if not isinstance(entry_id, str) or entry_id == "": raise BadRequest(f"{where}.id must be a non-empty string") timestamp = item.get("timestamp") # In Python bool subclasses int (isinstance(True, int) is True), so reject bool explicitly. if not isinstance(timestamp, int) or isinstance(timestamp, bool) or timestamp < 0: raise BadRequest(f"{where}.timestamp must be a non-negative integer (ms since the epoch)") severity = item.get("severity") # Check isinstance(..., str) before `in SEVERITY_RANK` so unhashable lists do not raise TypeError. if not isinstance(severity, str) or severity not in SEVERITY_RANK: raise BadRequest(f"{where}.severity must be one of DEBUG, INFO, WARN, ERROR") message = item.get("message") if not isinstance(message, str): raise BadRequest(f"{where}.message must be a string") return {"id": entry_id, "timestamp": timestamp, "severity": severity, "message": message} def get_param(query, name): """Return the single string value for query parameter `name`, or None if absent.""" values = query.get(name) if values is None: return None if len(values) > 1: raise BadRequest(f"{name} is given more than once") return values[0] def int_param(query, name): """Parse an optional ASCII integer query parameter.""" text = get_param(query, name) if text is None: return None # Guard with regex because int() alone accepts whitespace (" 5"), underscores ("1_0"), and Unicode digits. if not INTEGER.fullmatch(text): raise BadRequest(f"{name} must be an integer") return int(text)- All-or-nothing batches: We validate every item in
Organize per-camera storage around `(timestamp, seq)` keys
Dumping every camera's logs into one flat list forces every query to scan all logs from all cameras (
O(N)). Instead, we index storage to match how clients actually query—by one camera and a time range:_cameras["dock-west"] -> CameraLog: seen_ids: {"m1", "m2", "m3", "m0"} # O(1) duplicate detection keys: [(4900, 3), (5000, 0), (5000, 1), (5200, 2)] # sorted (timestamp, arrival_seq) entries: [ m0 dict, m1 dict, m2 dict, m3 dict ] # parallel array of log dictsWhy pair
timestampwith a monotonically increasing arrival counterseq?- Deterministic tie-breaking: Two entries at timestamp
5000(m1arriving atseq=0, thenm2arriving atseq=1) keep their exact arrival order(5000, 0) < (5000, 1). - Unique cursor keys: Every stored entry has a strictly unique 2-tuple
(timestamp, seq), which makes pagination exact even across thousands of identical timestamps. - Fast common-case inserts: Cameras usually upload logs in chronological order, so
bisect.bisect_right(self.keys, key)lands at the very end (len(self.keys)), turninglist.insertinto anO(1)append; only delayed out-of-order logs shift elements.
import bisect class CameraLog: """In-memory log store for a single camera, kept sorted by (timestamp, arrival_seq).""" def __init__(self): # keys[i] = (timestamp_ms, arrival_seq) matching entries[i] = {"id", "timestamp", "severity", "message"}. self.keys = [] self.entries = [] # seen_ids holds every entry["id"] stored for this camera so retries deduplicate in O(1). self.seen_ids = set() def add(self, entry, seq): """Insert one validated entry in (timestamp, seq) order.""" key = (entry["timestamp"], seq) # Normal in-order logs land at len(self.keys) (fast O(1) append); late logs shift into place. insert_pos = bisect.bisect_right(self.keys, key) self.keys.insert(insert_pos, key) self.entries.insert(insert_pos, entry)- Deterministic tie-breaking: Two entries at timestamp
Query time ranges with binary search and cursor pagination
Python compares tuples element by element, and a shorter tuple is strictly smaller than any longer tuple sharing the same prefix:
(5000,) < (5000, 0) < (5000, 99). That gives us exact binary-search boundaries onself.keysinO(log n)time:keys: [(4900, 3), (5000, 0), (5000, 1), (5200, 2)] index: 0 1 2 3 ^ ^ lo = bisect_left((5000,)) hi = bisect_left((5200,)) slice [lo, hi) = indices 1..2 -> timestamps in [5000, 5200)For pagination, offset paging (
?offset=200) breaks whenever a delayed log with an old timestamp arrives between page 1 and page 2—inserting at index0shifts every later index right by1, causing page 2 to repeat the last entry of page 1!Instead, we use keyset (cursor) pagination:
next_cursorencodes the last returned entry's unique key"timestamp:seq". On the next request:- For
order == "asc",bisect_right(self.keys, after)jumps strictly afterafter. - For
order == "desc",bisect_left(self.keys, after)boundshistrictly beforeafter, then walks backward (range(hi - 1, lo - 1, -1)).
Finally, we scan for
limit + 1matching entries instead of stopping atlimit. Only if an extra(limit + 1)-th match exists do we pop it and emitnext_cursor; when exactlylimitentries match in total,next_cursorisNoneso the client never wastes an extra trip fetching an empty page.def query_entries(log, start, end, min_rank, order, limit, after): """Standalone view of CameraLog.query showing window + cursor + look-ahead paging.""" lo = 0 if start is None else bisect.bisect_left(log.keys, (start,)) hi = len(log.keys) if end is None else bisect.bisect_left(log.keys, (end,)) if order == "asc": if after is not None: lo = max(lo, bisect.bisect_right(log.keys, after)) positions = range(lo, hi) else: if after is not None: hi = min(hi, bisect.bisect_left(log.keys, after)) positions = range(hi - 1, lo - 1, -1) found_indices = [] for idx in positions: if SEVERITY_RANK[log.entries[idx]["severity"]] >= min_rank: found_indices.append(idx) if len(found_indices) > limit: break next_key = None if len(found_indices) > limit: found_indices.pop() next_key = log.keys[found_indices[-1]] return [dict(log.entries[idx]) for idx in found_indices], next_key- For
Protect shared state across threads and wire up HTTP
Because
ThreadingHTTPServerhandles each incoming request on its own thread, two threads uploading or reading simultaneously could race onseen_ids,keys, or_next_seq. For example, without a lock, two retries arriving together could both checkentry["id"] in log.seen_ids, both seeFalse, and store the same entry twice!We guard shared state with
self._lock = threading.Lock(), while keeping all CPU/parsing work (JSON decoding, schema validation, query parsing) outside the lock so a slow or malformed payload never stalls other threads:Thread A (POST): [parse JSON + validate 1000 items] ---> acquire _lock -> dedup + insert -> release Thread B (GET): [parse query params] -----------------> acquire _lock -> bisect + copy -> releaseAt the bottom of
solution.py,serve()wrapsCameraLogServerin Python's standard-libraryThreadingHTTPServer(routingGET,POST,PUT, andDELETEintohandleand emitting the HTTPAllowheader on405responses).Walk through Example 1 and Example 2
Follow our new examples step by step to verify every status code, sort key, and cursor transition:
1. Out-of-order upload (Example 1): POST /cameras/lobby-north/logs body: {"entries": [{"id": "ev-9", "timestamp": 1500, "severity": "INFO", "message": "stream steady"}, {"id": "ev-2", "timestamp": 1100, "severity": "ERROR", "message": "lens obstructed"}, {"id": "ev-5", "timestamp": 1300, "severity": "WARN", "message": "bitrate drop"}]} -> 201 {"camera_id": "lobby-north", "stored": 3, "duplicates": 0} Internal keys: [(1100, 1), (1300, 2), (1500, 0)] (ev-9 arrived first -> seq 0, sorted to index 2) 2. Timeout retry of the identical batch: POST /cameras/lobby-north/logs (same body) -> 200 {"camera_id": "lobby-north", "stored": 0, "duplicates": 3} 3. Half-open window + severity filter: GET /cameras/lobby-north/logs?start=1100&end=1500&min_severity=WARN -> window [1100, 1500) excludes ev-9@1500; returns [ev-2, ev-5], "next_cursor": None 4. Tied timestamps + paginated read (Example 2): POST /cameras/dock-west/logs (m1@5000 DEBUG, m2@5000 INFO, m3@5200 INFO) GET /cameras/dock-west/logs?limit=2 -> 200 {"camera_id": "dock-west", "entries": [m1, m2], "next_cursor": "5000:1"} GET /cameras/dock-west/logs?limit=2&cursor=5000:1 -> bisect_right(keys, (5000, 1)) == 2 -> returns [m3], "next_cursor": None 5. Error responses: GET /cameras/unknown-cam/logs -> 404 {"error": "unknown camera: unknown-cam"} GET /cameras/lobby-north/logs?limit=0 -> 400 {"error": "limit must be between 1 and 1000"} DELETE /cameras/dock-west/logs -> 405 {"error": "method not allowed", "allowed": ["GET", "POST"]}Complete solution
from typing import Any, Dict, Optional, Tuple, Union import bisect import json import re import threading from urllib.parse import parse_qs, unquote, urlsplit SEVERITY_RANK = {"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3} MAX_BATCH = 1000 DEFAULT_LIMIT = 100 MAX_LIMIT = 1000 QUERY_PARAMS = {"start", "end", "min_severity", "order", "limit", "cursor"} CAMERA_ID = re.compile(r"[A-Za-z0-9_-]{1,64}") INTEGER = re.compile(r"-?[0-9]+") class BadRequest(Exception): """Raised whenever request validation fails; handle() converts it into HTTP 400.""" # ---------- storage ---------- class CameraLog: """In-memory log store for a single camera, kept sorted by (timestamp, arrival_seq).""" def __init__(self): # keys[i] = (timestamp_ms, arrival_seq) matching entries[i] = {"id", "timestamp", "severity", "message"}. self.keys = [] self.entries = [] # seen_ids holds every entry["id"] stored for this camera so retries deduplicate in O(1). self.seen_ids = set() def add(self, entry, seq): """Insert one validated entry in (timestamp, seq) order.""" key = (entry["timestamp"], seq) # Normal in-order logs land at len(self.keys) (fast O(1) append); late logs shift into place. insert_pos = bisect.bisect_right(self.keys, key) self.keys.insert(insert_pos, key) self.entries.insert(insert_pos, entry) def query(self, start, end, min_rank, order, limit, after): """Return (page_entries, next_cursor_key) for the half-open time window [start, end).""" if start is None: lo = 0 else: # A 1-tuple (start,) sorts strictly before every 2-tuple (start, seq), # so bisect_left lands on the first entry with timestamp >= start. lo = bisect.bisect_left(self.keys, (start,)) if end is None: hi = len(self.keys) else: # Landing on the first entry with timestamp >= end excludes timestamp == end ([start, end)). hi = bisect.bisect_left(self.keys, (end,)) # Narrow the index range strictly past the previous page's cursor key `after`. if order == "asc": if after is not None: lo = max(lo, bisect.bisect_right(self.keys, after)) positions = range(lo, hi) else: if after is not None: hi = min(hi, bisect.bisect_left(self.keys, after)) positions = range(hi - 1, lo - 1, -1) # Collect up to `limit + 1` matching indices; the extra item proves another page exists. found_indices = [] for idx in positions: entry_rank = SEVERITY_RANK[self.entries[idx]["severity"]] if entry_rank >= min_rank: found_indices.append(idx) if len(found_indices) > limit: break next_key = None if len(found_indices) > limit: found_indices.pop() next_key = self.keys[found_indices[-1]] # Return shallow copies so callers cannot mutate the server's stored dicts. page = [] for idx in found_indices: page.append(dict(self.entries[idx])) return page, next_key # ---------- request parsing ---------- def check_camera_id(camera_id): """Ensure camera_id has 1..64 safe URL characters.""" if not CAMERA_ID.fullmatch(camera_id): raise BadRequest("camera_id must be 1-64 characters from A-Z a-z 0-9 _ -") def parse_json_body(body): """Decode a str or bytes request body as JSON, raising BadRequest on empty or invalid input.""" if body is None or len(body) == 0: raise BadRequest("a JSON request body is required") try: return json.loads(body) except ValueError: # Both json.JSONDecodeError and UnicodeDecodeError inherit from ValueError. raise BadRequest("the request body is not valid JSON") def parse_entry(item, index): """Validate one uploaded log object and return a normalized dict.""" where = f"entries[{index}]" if not isinstance(item, dict): raise BadRequest(f"{where} must be an object") entry_id = item.get("id") if not isinstance(entry_id, str) or entry_id == "": raise BadRequest(f"{where}.id must be a non-empty string") timestamp = item.get("timestamp") # In Python bool subclasses int (isinstance(True, int) is True), so reject bool explicitly. if not isinstance(timestamp, int) or isinstance(timestamp, bool) or timestamp < 0: raise BadRequest(f"{where}.timestamp must be a non-negative integer (ms since the epoch)") severity = item.get("severity") # Check isinstance(..., str) before `in SEVERITY_RANK` so unhashable lists do not raise TypeError. if not isinstance(severity, str) or severity not in SEVERITY_RANK: raise BadRequest(f"{where}.severity must be one of DEBUG, INFO, WARN, ERROR") message = item.get("message") if not isinstance(message, str): raise BadRequest(f"{where}.message must be a string") return {"id": entry_id, "timestamp": timestamp, "severity": severity, "message": message} def get_param(query, name): """Return the single string value for query parameter `name`, or None if absent.""" values = query.get(name) if values is None: return None if len(values) > 1: raise BadRequest(f"{name} is given more than once") return values[0] def int_param(query, name): """Parse an optional ASCII integer query parameter.""" text = get_param(query, name) if text is None: return None # Guard with regex because int() alone accepts whitespace (" 5"), underscores ("1_0"), and Unicode digits. if not INTEGER.fullmatch(text): raise BadRequest(f"{name} must be an integer") return int(text) def format_cursor(key): """Encode a (timestamp, seq) tuple as 'timestamp:seq', or None on the final page.""" if key is None: return None return f"{key[0]}:{key[1]}" def parse_cursor(text): """Decode a 'timestamp:seq' cursor string back into an integer 2-tuple.""" if text is None: return None parts = text.split(":") if len(parts) != 2 or not INTEGER.fullmatch(parts[0]) or not INTEGER.fullmatch(parts[1]): raise BadRequest("cursor is not valid") return (int(parts[0]), int(parts[1])) # ---------- the server ---------- class CameraLogServer: def __init__(self) -> None: """In-memory storage for every camera's log entries. Requests may arrive on many threads.""" # _cameras maps camera_id (str) -> CameraLog instance created on first valid upload. self._cameras: Dict[str, CameraLog] = {} # Monotonic arrival counter used to break ties deterministically when timestamps match. self._next_seq = 0 # Mutex protecting _cameras, per-camera lists/sets, and _next_seq across request threads. self._lock = threading.Lock() def handle(self, method: str, path: str, body: Optional[Union[str, bytes]] = None) -> Tuple[int, Dict[str, Any]]: """Serve one HTTP request and return (status code, JSON body as a dict).""" try: return self._route(method, path, body) except BadRequest as exc: return 400, {"error": str(exc)} def _route(self, method, path, body): url = urlsplit(path) # Split on "/" before unquoting so an encoded "%2F" stays inside one segment and fails check_camera_id. segments = [] for part in url.path.split("/"): if part: segments.append(unquote(part)) # keep_blank_values=True retains empty parameters like "?limit=" so int_param rejects them with 400. query = parse_qs(url.query, keep_blank_values=True) if segments == ["cameras"]: if method != "GET": return 405, {"error": "method not allowed", "allowed": ["GET"]} return self._list_cameras() if len(segments) == 3 and segments[0] == "cameras" and segments[2] == "logs": camera_id = segments[1] if method == "POST": return self._upload(camera_id, body) if method == "GET": return self._read(camera_id, query) return 405, {"error": "method not allowed", "allowed": ["GET", "POST"]} return 404, {"error": "no such endpoint"} def _list_cameras(self): with self._lock: names = sorted(self._cameras) return 200, {"cameras": names} def _upload(self, camera_id, body): # Phase 1: parse and validate everything outside the lock so bad or slow payloads never block other threads. check_camera_id(camera_id) data = parse_json_body(body) if not isinstance(data, dict) or not isinstance(data.get("entries"), list): raise BadRequest('the body must be a JSON object with an "entries" list') raw_items = data["entries"] if len(raw_items) == 0: raise BadRequest('"entries" must not be empty') if len(raw_items) > MAX_BATCH: return 413, {"error": f"at most {MAX_BATCH} entries per request"} # All-or-nothing batch validation: if entry 7 is malformed, entries 0..6 are not stored either. validated_entries = [] for idx, item in enumerate(raw_items): validated_entries.append(parse_entry(item, idx)) # Phase 2: deduplicate and insert atomically under the lock. stored_count = 0 with self._lock: log = self._cameras.get(camera_id) if log is None: log = CameraLog() self._cameras[camera_id] = log for entry in validated_entries: if entry["id"] in log.seen_ids: continue log.seen_ids.add(entry["id"]) log.add(entry, self._next_seq) self._next_seq += 1 stored_count += 1 duplicate_count = len(validated_entries) - stored_count status = 201 if stored_count > 0 else 200 return status, {"camera_id": camera_id, "stored": stored_count, "duplicates": duplicate_count} def _read(self, camera_id, query): check_camera_id(camera_id) for name in query: if name not in QUERY_PARAMS: raise BadRequest(f"unknown query parameter: {name}") start = int_param(query, "start") end = int_param(query, "end") if start is not None and end is not None and start > end: raise BadRequest("start must not be greater than end") min_severity = get_param(query, "min_severity") if min_severity is None: min_severity = "DEBUG" if min_severity not in SEVERITY_RANK: raise BadRequest("min_severity must be one of DEBUG, INFO, WARN, ERROR") order = get_param(query, "order") if order is None: order = "asc" if order not in ("asc", "desc"): raise BadRequest('order must be "asc" or "desc"') limit = int_param(query, "limit") if limit is None: limit = DEFAULT_LIMIT if not 1 <= limit <= MAX_LIMIT: raise BadRequest(f"limit must be between 1 and {MAX_LIMIT}") after = parse_cursor(get_param(query, "cursor")) with self._lock: log = self._cameras.get(camera_id) if log is None: return 404, {"error": f"unknown camera: {camera_id}"} min_rank = SEVERITY_RANK[min_severity] page, next_key = log.query(start, end, min_rank, order, limit, after) return 200, {"camera_id": camera_id, "entries": page, "next_cursor": format_cursor(next_key)} # ---------- HTTP adapter (standard library; one thread per request) ---------- def serve(server: CameraLogServer, host: str = "127.0.0.1", port: int = 8080) -> None: from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class Handler(BaseHTTPRequestHandler): def dispatch(self): raw_length = self.headers.get("Content-Length") if raw_length is None: body = None elif not INTEGER.fullmatch(raw_length) or int(raw_length) < 0: status, payload = 400, {"error": "invalid Content-Length header"} self._write_json(status, payload) return else: length = int(raw_length) body = self.rfile.read(length) if length > 0 else None status, payload = server.handle(self.command, self.path, body) self._write_json(status, payload) def _write_json(self, status, payload): data = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) if status == 405: self.send_header("Allow", ", ".join(payload["allowed"])) self.end_headers() self.wfile.write(data) def do_GET(self): self.dispatch() def do_POST(self): self.dispatch() def do_PUT(self): self.dispatch() def do_DELETE(self): self.dispatch() ThreadingHTTPServer((host, port), Handler).serve_forever() if __name__ == "__main__": serve(CameraLogServer())✅ Submit now — all tests should pass.
Intuition & how it works
Think of this middle-tier server like a well-organized mailroom sitting between thousands of security cameras and the users inspecting them. Instead of tossing every incoming postcard into one giant bin on the floor, the mailroom gives each camera its own filing drawer, keeps folders inside that drawer sorted chronologically, and checks a stamp logbook (seen_ids) before filing anything so a camera that resends a batch after a network hiccup never creates duplicate folders.
A naive server that appends every uploaded entry to one global Python list and pages through results using numeric offsets (entries[offset : offset + limit]) breaks down immediately. First, reading 10 logs for one camera scans millions of unrelated logs from every other camera. Second, network delays deliver logs out of order—if an older log arrives while a user is clicking from Page 1 to Page 2, inserting that older log shifts every index right by 1 and causes Page 2 to repeat an entry from Page 1! Third, storing early items of a malformed batch or mutating lists across threads without a mutex lock (a synchronization primitive ensuring only one thread modifies shared memory at a time) corrupts state under retries and concurrency.
Walk through our 3-log Example 1 on "lobby-north" to see how our design solves all three problems:
"lobby-north"uploads[ev-9@1500, ev-2@1100, ev-5@1300]. We validate all 3 items outside the lock, then acquire_lock, assign arrival numbersseq = 0, 1, 2, record"ev-9", "ev-2", "ev-5"inseen_ids, and insert into sortedkeys = [(1100, 1), (1300, 2), (1500, 0)], returning201(stored: 3)."lobby-north"times out and resends the same batch. All 3 IDs hitseen_ids, giving idempotency (performing the same request once or multiple times produces the exact same stored state) and returning200(stored: 0, duplicates: 3).- A client calls
GET /cameras/lobby-north/logs?limit=2. Binary search (repeatedly halving a sorted array to find a boundary inO(log n)comparisons) locates the window, scanslimit + 1 = 3items to prove another page exists, returns[ev-2, ev-5]with cursor pagination tokennext_cursor = "1300:2"(bookmarking the exact(timestamp, seq)key of the last returned item), and resumes cleanly at[ev-9](next_cursor = None) on the next request.
Complexity
Let n be the number of stored entries for the target camera, b be the number of entries in an uploaded batch, and C be the number of known cameras:
- Upload (
POST /cameras/{id}/logs) — TimeO(b log n)in-order (O(b * n)worst-case out-of-order), SpaceO(b): Validating the JSON batch scansbitems once (O(b)). For each new entry, checkingseen_idsisO(1)on average andbisect_righttakesO(log n)comparisons; when timestamps arrive in chronological order, inserting at the end of the Python list is an amortizedO(1)append (whereas inserting a delayed older timestamp shifts up tonelements inO(n)). - Read (
GET /cameras/{id}/logs) — TimeO(log n + s), SpaceO(limit): Binary searches forstart,end, andcursoreach inspect at most~log2(n)keys (~20comparisons for1,000,000logs), and the loop then scanssentries inside that range untillimit + 1entries passmin_severity(s <= limit + 1whenmin_severity=DEBUG, or up tohi - loif matching severities are rare) and copies at mostlimitdicts for the response. - List cameras (
GET /cameras) — TimeO(C log C), SpaceO(C): Copies and sorts theCcamera ID strings alphabetically. - Total server memory — Space
O(total unique entries across all cameras): Each unique log entry is stored once alongside one(timestamp, seq)tuple inkeysand one string ID inseen_ids.
Edge cases
- Duplicate IDs within the same batch (
[x5, x5]): Becauseseen_ids.addruns immediately per item inside the upload loop, the firstx5is stored and the secondx5is counted induplicates. - Entire batch already seen: Returns
200 OK(stored: 0) rather than201 Createdso retrying clients treat the retry as a clean success. - Identical timestamps: Tied timestamps keep their exact arrival order via
(timestamp, seq), preventing cursor skips or duplicates across page boundaries. - Half-open empty window (
start == end): A half-open interval[start, end)includesstartand excludesend, sostart=150&end=150cleanly returns200withentries: [], whereasstart > endreturns400. - Exact page-size multiple (
len == limit): Scanning up tolimit + 1ensures that when exactlylimitentries match,next_cursorisNonerather than sending the client to a pointless empty trailing page. - URL encoding and trailing slashes:
/cameras/lobby-north/logs/ignores empty segments cleanly, while/cameras/bad%20id/logsdecodesbad%20idinto"bad id"after splitting on"/"and rejects it with400. - Python type traps (
bool,int()quirks,bytesbodies):timestamp = True,limit=1_0,start=%201, non-ASCII digits (limit=٣), and invalid UTF-8bytesall return400without crashing.
Common mistakes
- Returning
200 OKwith an error message in the JSON body: HTTP clients, load balancers, and metrics dashboards rely on proper status codes (400,404,405,413). - Returning
200 {"entries": []}for an unknown camera: Masks client typos incamera_idinstead of signaling404 Not Found. - Partially storing a malformed batch: Storing
entries[0..6]before failing onentries[7]leaves half-written state when the camera fixesentries[7]and retries. - Holding the lock during JSON parsing and validation: Serializes CPU-heavy
json.loadsacross all threads; keep only the fast in-memory critical section (the tiny block of code reading or mutating shared structures) insidewith self._lock:. - Using numeric
offsetpagination: Late-arriving logs inserted before the current offset shift subsequent slices and cause duplicate or skipped entries across pages. - Silently ignoring unknown query parameters: Ignoring
?severity=ERRORreturnsDEBUGlogs when the caller thought they filtered toERROR; fail fast with400.
Alternative approaches
- Embedded SQLite store: A single table with
PRIMARY KEY (camera_id, entry_id)and composite index(camera_id, ts, seq)providesINSERT OR IGNOREdeduplication,O(log n)keyset pagination (WHERE (ts, seq) > (?, ?)), and disk persistence across restarts with minimal code. - Fine-grained per-camera locks + hourly buckets: Giving each
CameraLogits ownthreading.Lock(with a per-cameraseqcounter) lets uploads to"lobby-north"and"dock-west"run in parallel, and bucketing each camera's logs by hour keeps late-arrival insertions and retention deletes bounded to small lists.
Follow-up questions
- If tens of thousands of devices stream log batches around the clock, where will this single-process design bottleneck first, and how would you evolve the ingestion and storage tiers? In a single Python process, unbounded RAM growth, single-lock contention, and CPython's Global Interpreter Lock (GIL) on JSON parsing saturate first—for perspective,
100,000devices logging one200-byte entry per second generate20 MB/s(~1.7 TB/day). To scale, place stateless API servers behind a load balancer that validate compressed batches and append them to a durable message log partitioned bycamera_id(such as Kafka), with background consumers batch-writing into a time-partitioned store (such as Cassandra keyed by(camera_id, day)clustered by(timestamp, seq), or ClickHouse), returning429/503withRetry-Afterfor backpressure (signaling senders to slow down and buffer locally when ingestion is overloaded). - How would you redesign the read API so dashboards receive newly ingested log entries in real time without repeated polling? Add
GET /cameras/{camera_id}/logs/streamusing Server-Sent Events (SSE) (a standard HTTPtext/event-streamresponse that keeps one connection open and pushes newline-delimited events from server to client). Stamp each pushed event'sid:with its monotonic arrival numberseq(nottimestamp:seq, because a delayed log with an older timestamp still has a newerseq!) so reconnecting clients sendLast-Event-IDto replay missed arrivals without gaps, and drop or disconnect slow subscribers whose per-connection queue fills up so they never stall uploads. - When an upload request times out on the network and the device retries the payload, how do you guarantee duplicate entries are not persisted? Have each device stamp every log entry at creation time with a camera-unique
id(for instance,<boot_uuid>-<local_counter>) and enforce uniqueness on(camera_id, entry_id)—implemented here vialog.seen_idsunder_lock, and in production via a database primary key or a bounded time-windowed deduplication cache. Per-entry IDs are stronger than a batch-levelIdempotency-Keyheader because they still deduplicate cleanly even if firmware coalesces two timed-out batches into a larger retry batch. - Suppose compliance rules require purging logs older than a fixed retention window. How can you expire old data without degrading read or write latency? Partition storage by time (for example, 1-hour in-memory ring buckets or daily database partitions with native TTL) so a background sweeper drops whole expired buckets in
O(1)rather than deleting individual rows on the request path. Simultaneously clamp every read'sstarttomax(start, now - retention_ms)so expired entries become invisible at the exact retention boundary even before the background sweep runs, and evict expired buckets' IDs (by keepingseen_idsper time bucket) so deduplication memory stays bounded too.
Follow-up questions
- If tens of thousands of devices stream log batches around the clock, where will this single-process design bottleneck first, and how would you evolve the ingestion and storage tiers?
- How would you redesign the read API so dashboards receive newly ingested log entries in real time without repeated polling?
- When an upload request times out on the network and the device retries the payload, how do you guarantee duplicate entries are not persisted?
- Suppose compliance rules require purging logs older than a fixed retention window. How can you expire old data without degrading read or write latency?
Similar questions
- Filterable Camera Dashboard
- Responsive Camera Grid View Model and Layout Spec
- Frame-by-Frame Media Player Controller
- Constant-Memory Generator Parser for Quoted Key-Value Logs
- Fleet-Scale Security Camera Liveness and Offline Monitoring
- Hierarchical Camera Authorization Service
More Verkada interview questions
- Detect Contiguous Active Sensor Windows Medium
- Fleet-Scale Security Camera Liveness and Offline Monitoring Medium
- Find the User Reaching All Cameras via Transitive Group Membership Medium Pro
- Design O(1) LRU and LFU In-Memory Caches Medium Pro
- Score Letter Feedback for Word Guesses Hard Pro
- Simultaneous High-Motion Intervals Across Camera Feeds Hard Pro
- Constant-Memory Generator Parser for Quoted Key-Value Logs Medium Pro
- Filterable Camera Dashboard Medium Pro
- Camera Fleet Health Monitoring Medium Pro
- Hierarchical Camera Authorization Service Hard Pro