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

  1. Ingest a batch — POST /cameras/{camera_id}/logs

    • The request body (str or UTF-8 bytes) must parse as a JSON object {"entries": [...]} containing between 1 and 1000 log entry objects:
      • "id": non-empty str, unique within that camera_id.
      • "timestamp": non-negative int representing epoch milliseconds (bool and float values are invalid).
      • "severity": str, one of "DEBUG", "INFO", "WARN", or "ERROR", ordered "DEBUG" < "INFO" < "WARN" < "ERROR".
      • "message": str.
    • Batch validation: If camera_id is invalid, body is missing or malformed JSON, "entries" is missing, not a list, or empty, returns 400. If "entries" contains more than 1000 items, returns 413. If any element in "entries" fails field validation, reject the entire request with 400 without 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 that camera_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 status 201 when stored > 0, or status 200 when stored == 0.
  2. Query stored logs — GET /cameras/{camera_id}/logs

    • Supports optional query parameters:
      • start, end: ASCII base-10 integers filtering the half-open timestamp interval start <= timestamp < end (each bound is optional; start > end returns 400).
      • min_severity: minimum severity threshold to include (default "DEBUG").
      • order: "asc" (oldest first, default) or "desc" (newest first). Entries sharing the exact same timestamp keep their original arrival order under "asc" and reverse arrival order under "desc".
      • limit: integer page size in 1..1000 (default 100).
      • 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_id values, 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 with 400.
    • If camera_id has never completed a valid upload, return 404.
    • Otherwise return 200 with {"camera_id": camera_id, "entries": [...], "next_cursor": <str or None>}, setting "next_cursor" to None when no further matching entries exist.
  3. List registered cameras — GET /cameras

    • Return 200 with {"cameras": [...]} containing all registered camera_id strings in ascending lexicographical order.
  4. Path and method errors

    • camera_id must match ^[A-Za-z0-9_-]{1,64}$ after splitting the URL path on "/" and percent-decoding each non-empty segment (otherwise 400).
    • Return 404 for any unrecognized route, and 405 when 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_id consists of 1 to 64 characters from A-Z, a-z, 0-9, _, and -.
  • 1 <= len(entries) <= 1000 per valid POST (0 entries returns 400; > 1000 entries returns 413).
  • timestamp is an integer with timestamp >= 0 (bool and float are rejected).
  • 1 <= limit <= 1000 (default 100).
  • Entry "id" uniqueness is scoped per camera_id; two different cameras may reuse the same entry "id".
  • In-memory persistence for the lifetime of the CameraLogServer instance is sufficient, and concurrent handle(...) calls across multiple threads must remain race-free.

Step-by-step walkthrough

  1. 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), and message (string). Cameras upload batches (1..1000 entries per POST) to amortize HTTP overhead; a batch above 1000 returns 413.
    • Safe retries (idempotency): If a network timeout causes a device to resend a batch, entries whose id is already in that camera's seen_ids set are skipped rather than duplicated. Storing at least one new entry returns 201; a pure retry where stored == 0 returns 200.
    • 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 in camera_id (404) from a registered camera with zero matching logs in a window (200 with "entries": []).
    • Time-range, severity, ordering, and pagination: GET /cameras/{camera_id}/logs filters by half-open [start, end) (start <= timestamp < end, so adjacent windows [1000, 1500) and [1500, 2000) never double-count timestamp 1500), min_severity, order ("asc" or "desc"), limit (1..1000, default 100), and cursor.
    • Camera directory & routing errors: GET /cameras lists registered camera IDs in sorted order; unrecognized paths return 404 and unsupported HTTP methods return 405.
    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
    
  2. 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 call handle directly in microseconds while keeping the real socket adapter (ThreadingHTTPServer or Flask) thin.

    Three routing details prevent subtle bugs:

    1. Raise BadRequest on validation failures: Catching BadRequest once in handle() turns any bad input into 400 {"error": ...} without cluttering every helper with if err: return 400.
    2. Split on "/" before URL-decoding (unquote): That way, a percent-encoded slash inside a camera ID (/cameras/bad%2Fid/logs) stays inside segments[1] == "bad/id" and gets rejected as an invalid camera_id (400) instead of looking like an extra URL segment.
    3. Pass keep_blank_values=True to parse_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 with 400.
    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"}
    
  3. 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 entries before touching storage. If entries[7] is malformed, entries[0..6] are not stored and a rejected batch never registers a phantom camera.
    • Python's bool and unhashable traps: isinstance(True, int) is True in Python, so parse_entry rejects bool explicitly on timestamp. Similarly, checking isinstance(severity, str) before severity in SEVERITY_RANK prevents ["INFO"] in SEVERITY_RANK from crashing with TypeError: unhashable type: 'list'.
    • Strict query parameters: Unknown parameter names (such as a typo ?severity=ERROR instead of ?min_severity=ERROR), duplicate parameters (?start=1&start=2), and non-ASCII/underscored integers (limit=1_0 or start=%201, which Python's int() would quietly accept!) all fail with 400.
    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)
    
  4. 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 dicts
    

    Why pair timestamp with a monotonically increasing arrival counter seq?

    1. Deterministic tie-breaking: Two entries at timestamp 5000 (m1 arriving at seq=0, then m2 arriving at seq=1) keep their exact arrival order (5000, 0) < (5000, 1).
    2. Unique cursor keys: Every stored entry has a strictly unique 2-tuple (timestamp, seq), which makes pagination exact even across thousands of identical timestamps.
    3. 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)), turning list.insert into an O(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)
    
  5. 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 on self.keys in O(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 index 0 shifts every later index right by 1, causing page 2 to repeat the last entry of page 1!

    Instead, we use keyset (cursor) pagination: next_cursor encodes the last returned entry's unique key "timestamp:seq". On the next request:

    • For order == "asc", bisect_right(self.keys, after) jumps strictly after after.
    • For order == "desc", bisect_left(self.keys, after) bounds hi strictly before after, then walks backward (range(hi - 1, lo - 1, -1)).

    Finally, we scan for limit + 1 matching entries instead of stopping at limit. Only if an extra (limit + 1)-th match exists do we pop it and emit next_cursor; when exactly limit entries match in total, next_cursor is None so 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
    
  6. Protect shared state across threads and wire up HTTP

    Because ThreadingHTTPServer handles each incoming request on its own thread, two threads uploading or reading simultaneously could race on seen_ids, keys, or _next_seq. For example, without a lock, two retries arriving together could both check entry["id"] in log.seen_ids, both see False, 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  -> release
    

    At the bottom of solution.py, serve() wraps CameraLogServer in Python's standard-library ThreadingHTTPServer (routing GET, POST, PUT, and DELETE into handle and emitting the HTTP Allow header on 405 responses).

  7. 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"]}
    
  8. 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:

  1. "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 numbers seq = 0, 1, 2, record "ev-9", "ev-2", "ev-5" in seen_ids, and insert into sorted keys = [(1100, 1), (1300, 2), (1500, 0)], returning 201 (stored: 3).
  2. "lobby-north" times out and resends the same batch. All 3 IDs hit seen_ids, giving idempotency (performing the same request once or multiple times produces the exact same stored state) and returning 200 (stored: 0, duplicates: 3).
  3. A client calls GET /cameras/lobby-north/logs?limit=2. Binary search (repeatedly halving a sorted array to find a boundary in O(log n) comparisons) locates the window, scans limit + 1 = 3 items to prove another page exists, returns [ev-2, ev-5] with cursor pagination token next_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) — Time O(b log n) in-order (O(b * n) worst-case out-of-order), Space O(b): Validating the JSON batch scans b items once (O(b)). For each new entry, checking seen_ids is O(1) on average and bisect_right takes O(log n) comparisons; when timestamps arrive in chronological order, inserting at the end of the Python list is an amortized O(1) append (whereas inserting a delayed older timestamp shifts up to n elements in O(n)).
  • Read (GET /cameras/{id}/logs) — Time O(log n + s), Space O(limit): Binary searches for start, end, and cursor each inspect at most ~log2(n) keys (~20 comparisons for 1,000,000 logs), and the loop then scans s entries inside that range until limit + 1 entries pass min_severity (s <= limit + 1 when min_severity=DEBUG, or up to hi - lo if matching severities are rare) and copies at most limit dicts for the response.
  • List cameras (GET /cameras) — Time O(C log C), Space O(C): Copies and sorts the C camera 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 in keys and one string ID in seen_ids.

Edge cases

  • Duplicate IDs within the same batch ([x5, x5]): Because seen_ids.add runs immediately per item inside the upload loop, the first x5 is stored and the second x5 is counted in duplicates.
  • Entire batch already seen: Returns 200 OK (stored: 0) rather than 201 Created so 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) includes start and excludes end, so start=150&end=150 cleanly returns 200 with entries: [], whereas start > end returns 400.
  • Exact page-size multiple (len == limit): Scanning up to limit + 1 ensures that when exactly limit entries match, next_cursor is None rather 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/logs decodes bad%20id into "bad id" after splitting on "/" and rejects it with 400.
  • Python type traps (bool, int() quirks, bytes bodies): timestamp = True, limit=1_0, start=%201, non-ASCII digits (limit=٣), and invalid UTF-8 bytes all return 400 without crashing.

Common mistakes

  • Returning 200 OK with 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 in camera_id instead of signaling 404 Not Found.
  • Partially storing a malformed batch: Storing entries[0..6] before failing on entries[7] leaves half-written state when the camera fixes entries[7] and retries.
  • Holding the lock during JSON parsing and validation: Serializes CPU-heavy json.loads across all threads; keep only the fast in-memory critical section (the tiny block of code reading or mutating shared structures) inside with self._lock:.
  • Using numeric offset pagination: 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=ERROR returns DEBUG logs when the caller thought they filtered to ERROR; fail fast with 400.

Alternative approaches

  • Embedded SQLite store: A single table with PRIMARY KEY (camera_id, entry_id) and composite index (camera_id, ts, seq) provides INSERT OR IGNORE deduplication, 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 CameraLog its own threading.Lock (with a per-camera seq counter) 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,000 devices logging one 200-byte entry per second generate 20 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 by camera_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), returning 429/503 with Retry-After for 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/stream using Server-Sent Events (SSE) (a standard HTTP text/event-stream response that keeps one connection open and pushes newline-delimited events from server to client). Stamp each pushed event's id: with its monotonic arrival number seq (not timestamp:seq, because a delayed log with an older timestamp still has a newer seq!) so reconnecting clients send Last-Event-ID to 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 via log.seen_ids under _lock, and in production via a database primary key or a bounded time-windowed deduplication cache. Per-entry IDs are stronger than a batch-level Idempotency-Key header 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's start to max(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 keeping seen_ids per time bucket) so deduplication memory stays bounded too.

Follow-up questions

Similar questions

More Verkada interview questions

All 21 Verkada questions →