Reservation Auxiliary Notes with Bulk Admin Edits

Medium · System Design · Software Engineer · Onsite

Prompt

Design an object-oriented domain model and supporting backend architecture for managing auxiliary comments attached to reservations on a multi-tenant travel or hospitality booking platform.

Your design should support these capabilities and extensions:

  • Reservation special-request notes: Each reservation can carry an auxiliary comment representing guest or traveler instructions (for instance, "Feather-free pillows requested" or "Arriving via evening shuttle").
  • Role-based editing: Standard users may create (and, if your design permits, modify or clear) the auxiliary comment on their own booking, whereas administrators can update the auxiliary comment on any reservation within their authorized scope.
  • Bulk administrative updates: Administrators occasionally need to modify auxiliary comments across thousands of reservations in a single operation (for instance, appending "Shuttle pickup relocated to North Curb" to every upcoming stay at a property).

State and justify your explicit assumptions on the open modeling choices:

  • Whether a reservation exposes a single active comment string, an append-only list, or an active field backed by versioned history.
  • What level of audit logging is required (capturing actor identity, timestamp, reason, and before/after values).
  • Realistic storage, read/write traffic, and bulk-job scale targets that shape your database and worker design.

Scope & Expectations

  • Object-oriented model & authorization: Define clean domain entities, value objects, and policy/service classes enforcing traveler ownership, tenant boundaries, and admin permissions.
  • Concurrency & auditability: Prevent lost updates when a traveler and an administrator edit the same reservation concurrently, and maintain a reliable audit trail.
  • APIs & persistence schema: Specify single-booking and batch-job endpoints alongside the underlying database tables and constraints.
  • Scalable bulk execution: Detail how multi-thousand-booking admin jobs preview blast radius, throttle database writes, isolate per-row failures, sync downstream suppliers, and support safe rollback.

Step-by-step walkthrough

  1. Clarify requirements and state assumptions

    Picture a corporate travel platform where employees book hotels, flights, and rental cars. Multiple customer organizations share the platform (multi-tenancy, meaning many companies use one system while each company's data stays strictly isolated). An auxiliary comment is a short special-request note attached to a booking — such as "Feather-free pillows requested" or "Arriving via evening shuttle" — viewed by the traveler, company travel admins, platform support agents, and the external hotel or car supplier.

    Explicit assumptions on modeling & scale

    1. Active string backed by versioned history: Store one active current comment per reservation plus an immutable append-only revision log of every change. External hotel and Global Distribution System (GDS) APIs accept a single special-request string rather than a chat thread, while the revision table preserves the complete chronological history of how that text evolved.
    2. Strict change-history tracking: Every edit atomically records the acting user's ID, their role and entry surface, the server timestamp, a mandatory justification whenever an admin or support agent edits another person's booking, and both the previous and updated strings.
    3. Traveler self-service lifecycle: Yes — the traveler (or an executive assistant who booked on their behalf) can create, update, or clear the comment on a confirmed upcoming reservation until its start time. Cancelled reservations cannot be edited by anyone because no active request should be sent to the supplier.
    4. Admin scope: An org admin can update comments only on reservations belonging to their own company (org_id), whereas an internal platform support agent can update comments across organizations when given a support ticket reason.

    Non-functional requirements

    • Zero cross-tenant leaks: Server-side authorization enforces ownership and org_id isolation on every read, single write, and batch job.
    • No lost updates: Concurrent edits by a traveler and an admin (or batch job) must never silently overwrite each other.
    • Fast interactive latency: Single comment reads < 100 ms and writes < 200 ms at p99.
    • Safe bulk execution: Batch updates across tens of thousands of reservations must be previewable, resumable, idempotent, reversible, and isolated so they never degrade live booking checkouts.
  2. Back-of-the-envelope numbers

    Because the prompt leaves scale open, we state realistic corporate-travel numbers up front and check what they imply for storage and throughput:

    Reservations & active comments
      new bookings per day            200,000 across all customer organizations
      online retention (3 years)      200,000 x 365 x 3          = ~220M reservations
      bookings with a comment (25%)   220M x 0.25                = ~55M current comments
    
    Interactive traffic
      comment writes per day          50,000 commented/day x 1.6 revisions = ~80,000 writes/day
      write rate                      80,000 / 86,400 s = ~1 write/s avg, ~10 writes/s peak
      read rate (trip pages, sync)    ~2M reads/day     = ~23 reads/s avg, ~250 reads/s peak
    
    Relational storage over 3 years
      current comments table          55M rows x ~250 B (text <= 500 chars + metadata) = ~14 GB
      revision history table          55M x 1.6 = 88M rows x ~400 B (old + new text)   = ~35 GB
      total storage                   ~49 GB -> fits comfortably inside PostgreSQL
    
    Admin batch updates
      typical batch size              1,000 to 50,000 reservations (hard cap: 200,000 per job)
      throttled DB write rate         500 reservations/s (~2,000 SQL statements/s across 4 tables)
      DB completion for 200k rows     200,000 / 500 rows/s       = 400 s (~6.7 minutes)
    
    External supplier sync (pushing updated special requests to hotel APIs)
      assumed hotel channel limit     20 requests/s per supplier integration
      200k bookings at ONE hotel chain 200,000 / 20 req/s        = 10,000 s (~2.8 hours)
    

    Three design conclusions jump right out of the math: 1. Storage is small (~50 GB in 3 years): Keep comments and revisions in the booking PostgreSQL database right next to reservations so permission checks and audit writes happen in one local ACID transaction. 2. Batch jobs are 50x write spikes: 500 updates/s is 50 times normal peak (~10/s), so batch workers must run in small throttled chunks rather than one giant SQL UPDATE. 3. External hotels are much slower than our database: Saving 200,000 comments takes ~7 minutes, while syncing them to a rate-limited hotel channel can take hours, so job progress must track database save status separately from supplier delivery status.

  3. Object-oriented domain model

    We separate responsibilities cleanly so every change — whether from the mobile app, the admin console, or a background batch worker — passes through the exact same permission check, text sanitizer, optimistic version check, and audit log writer:

     +-------------------+        checks         +----------------------+
     |  CommentService   | --------------------> |    CommentPolicy     |
     |  update(...)      |                       |  can_edit(actor,...) |
     +---------+---------+                       +----------------------+
               |
               | reads / writes inside one DB transaction
               v
     +-------------------+   1       0..1   +----------------------+   1       0..*   +-------------------+
     |    Reservation    | ---------------> |   AuxiliaryComment   | ---------------> |  CommentRevision  |
     | reservation_id    |                  | reservation_id       |                  | version (1, 2...) |
     | org_id, status    |                  | text, version        |                  | old_text, new_text|
     | traveler_id       |                  | updated_by, at       |                  | actor_id, reason  |
     +-------------------+                  +----------------------+                  +-------------------+
    

    Here is the core object-oriented model in Python:

    import unicodedata
    from dataclasses import dataclass
    from datetime import datetime
    from enum import Enum
    from typing import FrozenSet, Optional
    
    MAX_COMMENT_LENGTH = 500
    
    
    class Role(Enum):
        TRAVELER = "traveler"
        ORG_ADMIN = "org_admin"
        SUPPORT_AGENT = "support_agent"
    
    
    class ReservationStatus(Enum):
        CONFIRMED = "confirmed"
        COMPLETED = "completed"
        CANCELLED = "cancelled"
    
    
    class CommentOp(Enum):
        SET = "set"        # Replace the entire comment with new text
        APPEND = "append"  # Add a new line below any existing comment text
        CLEAR = "clear"    # Empty the comment back to ""
    
    
    class NotFoundError(Exception):
        pass
    
    
    class ForbiddenError(Exception):
        pass
    
    
    class InvalidCommentError(Exception):
        pass
    
    
    class VersionConflictError(Exception):
        """Raised when expected_version does not match the database row's current version."""
    
        def __init__(self, current_comment: "AuxiliaryComment"):
            super().__init__(f"Expected different version; current is v{current_comment.version}")
            self.current_comment = current_comment
    
    
    @dataclass(frozen=True)
    class Actor:
        # Authenticated caller extracted from SSO/JWT token (never trusted from request body)
        user_id: str
        org_id: str
        roles: FrozenSet[Role]
    
    
    @dataclass(frozen=True)
    class Reservation:
        reservation_id: str
        org_id: str
        traveler_id: str
        booked_by_id: str
        status: ReservationStatus
        starts_at: datetime
    
    
    @dataclass(frozen=True)
    class AuxiliaryComment:
        # Current state of a reservation's comment; version = 0 means never set yet
        reservation_id: str
        text: str
        version: int
        updated_by: Optional[str]
        updated_at: Optional[datetime]
    
    
    @dataclass(frozen=True)
    class CommentRevision:
        # Immutable audit record written on every effective text change
        reservation_id: str
        version: int
        old_text: str
        new_text: str
        actor_id: str
        source: str                 # "traveler_app", "admin_console", "support_tool", or "batch"
        batch_job_id: Optional[str]
        reason: Optional[str]
        created_at: datetime
    

    Next, CommentPolicy, text transformation helpers, and CommentService enforce all domain invariants in one place:

    def is_reservation_owner(actor: Actor, reservation: Reservation) -> bool:
        return actor.user_id in (reservation.traveler_id, reservation.booked_by_id)
    
    
    class CommentPolicy:
        """Central authorization rules for who may edit a reservation's auxiliary comment."""
    
        def can_edit(self, actor: Actor, reservation: Reservation, now: datetime) -> bool:
            # Cancelled bookings never accept new special requests for suppliers
            if reservation.status == ReservationStatus.CANCELLED:
                return False
    
            # Platform support agents can update non-cancelled bookings across organizations
            if Role.SUPPORT_AGENT in actor.roles:
                return True
    
            # Company travel admins can update non-cancelled bookings within their own organization
            if Role.ORG_ADMIN in actor.roles and actor.org_id == reservation.org_id:
                return True
    
            # Regular travelers/bookers can edit only their own upcoming confirmed booking
            is_upcoming = reservation.status == ReservationStatus.CONFIRMED and now < reservation.starts_at
            return is_reservation_owner(actor, reservation) and is_upcoming
    
    
    def sanitize_text(raw_text: str) -> str:
        """Normalize line endings and strip invisible control characters while preserving emoji/accents."""
        normalized_lines = raw_text.replace("\r\n", "\n").replace("\r", "\n")
        cleaned_chars: list[str] = []
        for ch in normalized_lines:
            # Unicode category "Cc" = control chars; keep '\n' and all printable/international chars
            if ch == "\n" or unicodedata.category(ch) != "Cc":
                cleaned_chars.append(ch)
        return "".join(cleaned_chars).strip()
    
    
    def compute_next_text(current_text: str, operation: CommentOp, incoming_text: str) -> str:
        if operation == CommentOp.CLEAR:
            return ""
    
        cleaned_note = sanitize_text(incoming_text)
        if cleaned_note == "":
            raise InvalidCommentError("Use CLEAR to empty a comment; SET/APPEND text cannot be blank")
    
        if operation == CommentOp.SET or current_text == "":
            candidate = cleaned_note
        else:
            candidate = f"{current_text}\n{cleaned_note}"
    
        if len(candidate) > MAX_COMMENT_LENGTH:
            raise InvalidCommentError(f"Comment exceeds {MAX_COMMENT_LENGTH} characters ({len(candidate)})")
        return candidate
    
    
    class CommentService:
        """Single transactional entry point used by user APIs, admin tools, and batch workers."""
    
        def __init__(self, store, policy: CommentPolicy, clock):
            self.store = store
            self.policy = policy
            self.clock = clock
    
        def update_comment(
            self,
            actor: Actor,
            reservation_id: str,
            operation: CommentOp,
            incoming_text: str,
            expected_version: Optional[int],
            source: str,
            reason: Optional[str] = None,
            batch_job_id: Optional[str] = None,
        ) -> AuxiliaryComment:
            reservation = self.store.get_reservation(reservation_id)
            if reservation is None:
                raise NotFoundError(reservation_id)
    
            now = self.clock.now()
            if not self.policy.can_edit(actor, reservation, now):
                raise ForbiddenError(reservation_id)
    
            # Any admin or support agent editing someone else's trip must provide an audit reason
            if not is_reservation_owner(actor, reservation) and not (reason and reason.strip()):
                raise InvalidCommentError("An audit reason is required when editing another user's booking")
    
            with self.store.transaction() as tx:
                # Lock the comment row (creating an empty version-0 row first if none exists yet)
                current = tx.lock_or_init_comment(reservation_id)
    
                if expected_version is not None and current.version != expected_version:
                    raise VersionConflictError(current)
    
                new_text = compute_next_text(current.text, operation, incoming_text)
                if new_text == current.text:
                    return current  # No-op: skip writing a redundant revision or outbox event
    
                updated = AuxiliaryComment(
                    reservation_id=reservation_id,
                    text=new_text,
                    version=current.version + 1,
                    updated_by=actor.user_id,
                    updated_at=now,
                )
                revision = CommentRevision(
                    reservation_id=reservation_id,
                    version=updated.version,
                    old_text=current.text,
                    new_text=new_text,
                    actor_id=actor.user_id,
                    source=source,
                    batch_job_id=batch_job_id,
                    reason=reason.strip() if reason else None,
                    created_at=now,
                )
                tx.save_comment(updated)
                tx.insert_revision(revision)
                tx.insert_outbox_event("aux_comment.changed", reservation_id, updated.version)
                return updated
    
  4. REST API for single edits and batch jobs

    For single reservations, we use standard HTTP ETag and If-Match headers — HTTP's built-in mechanism for passing a record's version number so the server rejects stale edits with 412 Precondition Failed instead of overwriting newer text:

    Single-reservation endpoints
      GET    /v1/reservations/{id}/aux-comment
             -> 200 OK, ETag: "3"
                { "text": "Feather-free pillows requested", "version": 3,
                  "updated_by": { "id": "u_304", "role": "traveler" },
                  "updated_at": "2026-12-02T18:10:00Z" }
                (If never set, returns text: "", version: 0, ETag: "0")
    
      PUT    /v1/reservations/{id}/aux-comment
             Headers: If-Match: "3", Idempotency-Key: "8a12..."
             Body:    { "operation": "set", "text": "Feather-free pillows; arriving via 21:45 shuttle.", "reason": null }
             -> 200 OK (version: 4, ETag: "4")
             -> 412 Precondition Failed { "current": { "text": "...", "version": 4 } }
             -> 403 Forbidden | 422 Unprocessable Entity (> 500 chars or missing admin reason)
    
      DELETE /v1/reservations/{id}/aux-comment   (Headers: If-Match: "4") -> clears text, creates v5
    
      GET    /v1/reservations/{id}/aux-comment/history?cursor=...
             -> paginated list of revisions (old_text, new_text, actor, role, reason, timestamp)
    

    For bulk admin updates, we expose an asynchronous preview-then-execute job resource so an admin always sees the exact blast radius before modifying thousands of trips:

    Batch admin endpoints
      POST /v1/admin/aux-comment-jobs
           { "selector": { "filter": { "supplier_id": "htl_denver_4",
                                       "starts_from": "2026-12-10", "starts_to": "2026-12-31",
                                       "status": ["confirmed"] } },   // org_id forced from admin JWT!
             "operation": "append",
             "text": "Shuttle pickup relocated to North Curb.",
             "reason": "Property operations notice #8830",
             "skip_if_changed": true }
           -> 201 Created
              { "job_id": "job_910", "status": "preview", "matched_count": 4212,
                "warnings": { "exceeds_max_length": 3 },
                "sample_diffs": [ { "reservation_id": "res_809", "before": "...", "after": "..." } ] }
    
      POST /v1/admin/aux-comment-jobs/{job_id}/start   -> 202 ("queued", or "pending_approval" if > 10k rows)
      POST /v1/admin/aux-comment-jobs/{job_id}/approve -> second admin sign-off for > 10k-row jobs
      POST /v1/admin/aux-comment-jobs/{job_id}/cancel  -> halts unclaimed chunks immediately
      POST /v1/admin/aux-comment-jobs/{job_id}/revert  -> 202 { "revert_job_id": "job_911" }
      GET  /v1/admin/aux-comment-jobs/{job_id}
           -> { "status": "running", "total": 4212, "done": 3000, "skipped": 12, "failed": 3,
                "supplier_sync": { "delivered": 2410, "pending": 575, "failed": 15 } }
    
  5. Relational storage schema

    Keeping comments in a dedicated aux_comments table inside the booking PostgreSQL database — rather than adding a wide column directly on reservations — means locking comment rows during a batch job never blocks concurrent flight or hotel status updates on reservations:

    -- 1. Current active comment (1 row per commented reservation; ~14 GB for 55M rows)
    CREATE TABLE aux_comments (
        reservation_id   TEXT PRIMARY KEY REFERENCES reservations(reservation_id),
        text             VARCHAR(500) NOT NULL,
        version          INT NOT NULL,
        updated_by       TEXT,
        updated_by_role  TEXT,
        updated_at       TIMESTAMPTZ
    );
    
    -- 2. Immutable append-only audit log (~35 GB for 88M revisions)
    -- App DB user is granted SELECT + INSERT only (no UPDATE or DELETE privileges)
    CREATE TABLE aux_comment_revisions (
        revision_id      BIGSERIAL PRIMARY KEY,
        reservation_id   TEXT NOT NULL REFERENCES reservations(reservation_id),
        version          INT NOT NULL,
        old_text         VARCHAR(500) NOT NULL,
        new_text         VARCHAR(500) NOT NULL,
        actor_id         TEXT NOT NULL,
        actor_role       TEXT NOT NULL,
        source           TEXT NOT NULL,
        batch_job_id     TEXT,
        reason           TEXT,
        created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
        UNIQUE (reservation_id, version),
        UNIQUE (batch_job_id, reservation_id)  -- guarantees a batch job mutates a booking at most once
    );
    
    -- 3. Batch job header and per-reservation work items
    CREATE TABLE aux_comment_jobs (
        job_id           TEXT PRIMARY KEY,
        org_scope        TEXT,                 -- NULL only for platform support agents
        created_by       TEXT NOT NULL,
        approved_by      TEXT,
        operation        TEXT NOT NULL,
        text             VARCHAR(500) NOT NULL,
        reason           TEXT NOT NULL,
        skip_if_changed  BOOLEAN NOT NULL DEFAULT true,
        status           TEXT NOT NULL,        -- preview, pending_approval, queued, running, done, cancelled
        total_count      INT NOT NULL,
        done_count       INT NOT NULL DEFAULT 0,
        skipped_count    INT NOT NULL DEFAULT 0,
        failed_count     INT NOT NULL DEFAULT 0,
        created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
    );
    
    CREATE TABLE aux_comment_job_items (
        job_id              TEXT NOT NULL REFERENCES aux_comment_jobs(job_id),
        reservation_id      TEXT NOT NULL,
        version_at_preview  INT NOT NULL,
        status              TEXT NOT NULL DEFAULT 'pending', -- pending, done, skipped, failed
        applied_version     INT,
        error_detail        TEXT,
        PRIMARY KEY (job_id, reservation_id)
    );
    
    -- 4. Transactional outbox for reliable event publishing
    CREATE TABLE outbox_events (
        event_id         BIGSERIAL PRIMARY KEY,
        aggregate_id     TEXT NOT NULL,        -- reservation_id (Kafka partition key)
        event_type       TEXT NOT NULL,
        payload          JSONB NOT NULL,
        created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
        published_at     TIMESTAMPTZ
    );
    

    Notice UNIQUE (batch_job_id, reservation_id) on aux_comment_revisions: in PostgreSQL, NULL values are treated as distinct by default, so manual edits (batch_job_id IS NULL) never collide, while any bug that tries to apply the same batch_job_id to a reservation twice fails immediately with a unique-constraint violation instead of appending duplicate text.

  6. High-level system architecture

    A transactional outbox (saving outgoing events into outbox_events in the exact same database transaction as the comment edit, then relaying them to Kafka asynchronously) guarantees that we never update the database without notifying downstream systems, or vice versa:

     Traveler Mobile / Web                     Org Admin Console / Support Tool
              |                                                |
              v                                                v
     [ API Gateway: SSO / JWT authentication, rate limiting, request_id tracing ]
              |                                                |
              v                                                v
     [ Reservation API ]                              [ Batch Comment-Job API ]
       CommentService.update_comment() <-------------   preview / start / approve / revert
       CommentPolicy.can_edit()                                |
              |                                                v
              |                                       [ Batch Worker Pool ]
              |  1 ACID tx: comment + revision          claims 200 items/chunk via SKIP LOCKED
              |             + outbox_events             throttled to 500 rows/s via token bucket
              v                                                |
     +---------------------------------------------------------+
     |
     v
     [ Booking PostgreSQL (Primary + Read Replicas) ]
       reservations | aux_comments | aux_comment_revisions | jobs & items | outbox_events
              |
              v  Outbox Relay polls unpublished rows
     [ Kafka Topic: reservation.aux_comment.changed (partitioned by reservation_id) ]
              |
              +---> [ Supplier Sync Workers ] --> Hotel / Car GDS APIs (rate-limited, 24h retry)
              +---> [ Notification Service ]  --> Push / Email to traveler when non-owner edits
              '---> [ WORM Audit Archive ]    --> Object-locked S3 archive for long-term compliance
    
  7. Deep dive 1: Authorization boundaries and concurrent edits

    Strict server-side tenant isolation: - The caller's user_id, org_id, and roles come exclusively from the verified JWT token at the API gateway — never from a query parameter or JSON field. - Batch jobs enforce org_id twice: first when expanding the preview query (WHERE reservations.org_id = :actor_org_id), and again inside CommentPolicy.can_edit for every individual row when the worker executes.

    Preventing lost updates with optimistic concurrency + short row locks: Optimistic concurrency control means we do not lock database rows while a human stares at an open edit dialog for five minutes; instead, the client sends back the version it read, and inside the short write transaction we acquire a pessimistic row lock (SELECT ... FOR UPDATE under PostgreSQL's READ COMMITTED isolation) for just ~1–2 milliseconds to verify the version and write atomically.

    Trace what happens when Traveler Maya and Batch Job job_910 edit Reservation res_809 concurrently:

    Time  Actor & action                                        DB state of res_809
    ----  ----------------------------------------------------  --------------------------------------------------
    t0    Maya opens trip screen: GET .../aux-comment           version = 3, text = "Feather-free pillows"
    t1    Batch worker runs APPEND ("Shuttle at North Curb")    SELECT FOR UPDATE -> sees v3 -> writes v4:
          with expected_version = None                          "Feather-free pillows\nShuttle at North Curb"
    t2    Maya clicks Save ("Feather-free pillows; 21:45")      SELECT FOR UPDATE -> sees v4 != If-Match "3"
          sending If-Match: "3"                                 -> returns 412 with v4's text!
    t3    Maya's UI displays both versions side by side;        SELECT FOR UPDATE -> sees v4 == If-Match "4"
          Maya confirms merged text with If-Match: "4"          -> writes v5 cleanly with zero lost notes!
    

    Why batch APPEND passes expected_version = None while batch SET/CLEAR uses version_at_preview: - An APPEND adds a policy line below whatever text currently exists under SELECT ... FOR UPDATE, so it safely preserves an edit Maya made after the preview. - A SET or CLEAR would wipe out Maya's newer edit; when skip_if_changed = true, passing expected_version = item.version_at_preview raises VersionConflictError, causing the worker to mark that item skipped instead of erasing Maya's recent note.

  8. Deep dive 2: Tamper-evident audit history and privacy

    Atomic history: Because aux_comment_revisions is written inside the same PostgreSQL transaction as aux_comments, it is impossible for a crash to leave an unrecorded edit or a phantom audit entry.

    Defense-in-depth immutability: 1. The application's PostgreSQL role only has SELECT and INSERT permissions on aux_comment_revisions (zero UPDATE or DELETE privileges). 2. Every outbox event also streams to a write-once-read-many (WORM) S3 audit bucket, so even someone with raw database admin credentials cannot silently alter historical records.

    Handling sensitive personal data (GDPR / privacy erasure): Auxiliary comments often contain health, accessibility, or religious details ("Wheelchair-accessible shower", "Kosher meal"). To reconcile audit immutability with privacy erasure laws: - A dedicated privileged erasure job replaces text, old_text, and new_text for that traveler's reservations with "[REDACTED_BY_PRIVACY_REQUEST]" while preserving actor_id, created_at, and reason, and appends an audit revision documenting the erasure itself. - In the WORM S3 archive, sensitive text payloads are encrypted using a per-traveler encryption key (crypto-shredding: deleting that traveler's key renders archived copies permanently unreadable without mutating immutable S3 objects). - Comments are always stored as plain text and HTML-escaped on render so a malicious string like <script>... can never execute inside an admin's browser.

  9. Deep dive 3: Safe, reversible batch updates at scale

    Updating 50,000–200,000 reservations safely requires four phases plus decoupled downstream sync:

    Phase 1: Preview (freeze target set)
      - Run admin's filter query with keyset pagination; insert matched reservation_ids + current
        comment versions into aux_comment_job_items.
      - Pre-check length warnings (e.g. existing 470-char comment + 60-char append > 500 chars) and
        return sample before/after diffs.
    
    Phase 2: Two-person approval (for jobs > 10,000 reservations)
      - Prevents a single mistyped filter from rewriting an entire enterprise's active trips.
    
    Phase 3: Chunked, throttled worker execution (200 items per transaction)
      BEGIN;
        -- Claim up to 200 pending items without blocking other workers
        SELECT reservation_id, version_at_preview
          FROM aux_comment_job_items
         WHERE job_id = :job_id AND status = 'pending'
         ORDER BY reservation_id
         LIMIT 200
         FOR UPDATE SKIP LOCKED;
    
        -- Process in sorted reservation_id order (prevents deadlocks between overlapping jobs!):
        --   SAVEPOINT item_sp;
        --   call CommentService.update_comment(...)
        --   on InvalidCommentError / ForbiddenError / VersionConflictError:
        --       ROLLBACK TO SAVEPOINT item_sp;
        --       mark item 'failed' or 'skipped' with reason (other 199 items succeed!)
        UPDATE aux_comment_jobs SET done_count = done_count + ... WHERE job_id = :job_id;
      COMMIT;
    
    Phase 4: One-click revert (if an admin pasted the wrong policy note)
      - Creates a revert job iterating over `done` items of the original job.
      - If current.version == item.applied_version, restores revision.old_text (creating version v+1).
      - If current.version > item.applied_version (traveler edited after the batch), skips and flags
        that booking rather than clobbering the traveler's newer edit.
    

    Two subtle database engineering details make Phase 3 bulletproof: - Database savepoints: A savepoint (SAVEPOINT item_sp) is a mini-checkpoint inside a SQL transaction. Without it, a single bad row or database error inside a 200-row chunk aborts the entire PostgreSQL transaction and rolls back 199 healthy updates. Rolling back to item_sp isolates each row's failure cleanly. - Adaptive throttling: Workers pull permits from a shared token bucket (a rate-limiting counter refilling at 500 rows/s per job and 1,000 rows/s globally) and automatically pause if PostgreSQL read-replica lag exceeds 5 seconds or checkout API p99 latency spikes.

    Decoupled supplier sync and coalescing: Downstream supplier-sync workers consume aux_comment.changed from Kafka (partitioned by reservation_id so updates per booking stay ordered), read the latest comment version from the primary DB (coalescing rapid back-to-back edits into one outbound supplier call), enforce each hotel channel's 20 req/s rate limit, and update supplier_sync counters independently so admins see both "4,212 saved in DB" and "2,410 delivered to hotel".

    Summary of key trade-offs - Single active comment + revision history vs. comment thread: Matches external supplier APIs (1 string) and keeps reads to 1 row, while preserving complete history. - Optimistic ETag/If-Match vs. locking on page open: Avoids long-held locks across 55M rows; requires a simple merge prompt in the UI on rare 412 conflicts. - Frozen preview item list vs. live SQL filter during execution: Guarantees exact preview counts and clean one-click reverts; future bookings created after preview are handled by standing policy rules instead. - 200-row SKIP LOCKED chunks with savepoints vs. one bulk UPDATE: Slightly more worker code, in exchange for zero booking lock stalls, per-row error isolation, crash resumability, and per-row audit revisions.

Intuition & how it works

Think of an auxiliary comment as the "Special Instructions" note clipped to a hotel reservation folder in a corporate travel office: the traveler, their company's travel manager, and platform support can all update it, the hotel front desk expects one clean instruction string at check-in, and compliance requires an indelible carbon copy of every single edit. To make both single edits and 50,000-booking policy updates safe, every write goes through one domain service (CommentService) that checks permissions, verifies a version number (optimistic concurrency control, attaching an integer version to each record so edits never hold long locks and stale saves are rejected cleanly), updates the active comment in its own aux_comments table, appends an immutable CommentRevision row, and queues a downstream notification in one atomic database transaction.

A naive design that adds a bare comment TEXT column onto reservations and overwrites it with plain UPDATE statements breaks in three ways immediately. First, if a traveler and an admin edit the same booking concurrently, the second save silently erases the first person's note. Second, overwriting in place leaves no record of who changed a note or what it used to say when a dispute or bad bulk edit happens. Third, an admin running one giant UPDATE reservations SET ... across 50,000 bookings holds database locks on reservations for seconds or minutes, stalling live flight and hotel checkouts.

Walk through how our design handles four events on Reservation res_809 (org_id = "org_horizon"):

Event 1: Traveler Maya opens her upcoming Denver hotel booking (currently no comment -> version 0)
  -> Maya sends PUT /v1/reservations/res_809/aux-comment with If-Match: "0" and "Feather-free pillows requested".
  -> CommentService checks Maya owns res_809, writes aux_comments (v1), inserts revision v1
     (old: "", new: "Feather-free pillows requested"), and writes an outbox event in ONE transaction.

Event 2: Travel Admin Devon previews and starts batch job_910 ("append 'Shuttle pickup relocated to North Curb' to 4,212 bookings")
  -> A batch worker claims a 200-row chunk, locks res_809's comment row, appends the note onto v1,
     writes v2 ("Feather-free pillows requested\nShuttle pickup relocated to North Curb"), logs revision v2
     with reason + job_910, and queues an alert to Maya + a rate-limited sync to the hotel API.

Event 3: Maya (whose phone screen still shows v1) adds "arriving 21:45" with If-Match: "1"
  -> Server sees current version is 2 != 1 -> returns 412 Precondition Failed with v2's text instead
     of wiping out Devon's shuttle relocation notice!

Event 4: Maya sees both texts side by side, keeps both ("Feather-free pillows; arriving 21:45\nShuttle pickup relocated to North Curb"),
         and submits with If-Match: "2" -> succeeds cleanly as version 3.

Key trade-offs

  • One active comment + immutable revision log vs. a multi-comment thread. Storing one current text string matches what external hotel and car supplier APIs accept and keeps every read to a single primary-key lookup, while aux_comment_revisions still preserves full history. A multi-message thread fits back-and-forth support chats, so if conversations are ever needed, model them as a separate reservation_messages feature rather than complicating supplier-bound special requests.
  • Optimistic concurrency (ETag / If-Match) vs. pessimistic locking while editing. ETag and If-Match are HTTP headers that pass the comment's version number on reads and writes so no database lock is held while a user types, which is ideal when peak write volume is ~10 writes/s spread across 55M comments. The small cost is handling rare 412 version conflicts in the UI by showing the latest text alongside the user's draft.
  • Same-transaction revision + transactional outbox vs. calling an external audit/event service. A transactional outbox writes outgoing events into a database table inside the same ACID transaction as the comment change and relays them to Kafka asynchronously, guaranteeing zero mismatch between the comment, its audit log, and downstream hotel syncs. Calling Kafka or an audit microservice directly from application code risks partial failures where the comment updates but the audit log or hotel notification is lost.
  • Freezing matched reservations at batch preview vs. running a live filter during execution. Materializing aux_comment_job_items during preview means the admin's preview count, execution scope, and one-click revert target the exact same set of bookings. Bookings created after the preview are not included, which is cleanly solved by standing policy rules when ongoing coverage is desired.
  • Chunked FOR UPDATE SKIP LOCKED workers + savepoints vs. one bulk SQL UPDATE. FOR UPDATE SKIP LOCKED (a SQL clause letting parallel workers claim non-overlapping rows without blocking each other) paired with 200-row chunks and token-bucket throttling (a steady rate-limit counter, e.g., 500 rows/s) takes more code than a single UPDATE, but keeps lock durations under half a second, survives worker crashes, records per-row failures, and protects live checkout latency.
  • Copying a batch policy note into each booking's comment vs. evaluating shared rules at read time. Copying into each comment keeps reads fast (one row) and records the exact string sent to each hotel at that version, at the cost of N throttled writes during a batch job.

Common mistakes

  • Enforcing permissions only in the frontend or trusting org_id from the request body, allowing a travel admin at Company A to view or overwrite comments belonging to Company B.
  • Allowing edits on cancelled reservations (especially inside admin batch jobs), which wastes supplier API quota and sends confusing "your booking comment changed" emails for cancelled trips.
  • Using last-write-wins without version checks, causing a traveler's minor typo fix to silently delete an urgent policy note appended moments earlier by an admin batch job.
  • Making batch APPEND non-idempotent, so a worker crash and retry appends the same policy paragraph two or three times onto thousands of reservations (prevented here by updating aux_comment_job_items.status in the same transaction and enforcing UNIQUE (batch_job_id, reservation_id) on revisions).
  • Running a 200-row batch chunk without per-row database savepoints — a savepoint is a mini-checkpoint inside a SQL transaction; without it, one comment exceeding 500 characters or hitting a constraint error rolls back all 199 valid updates in that chunk.
  • Reporting a batch job as "completed" as soon as PostgreSQL finishes, hiding the fact that rate-limited external hotel APIs (at ~20 req/s) may take another two hours to receive all 200,000 updates.
  • Rendering free-text comments unescaped in admin tools or ignoring privacy erasure, exposing admins to XSS injection and leaving sensitive health/dietary notes ("wheelchair room", "kosher meal") permanently unredacted without a redaction workflow or crypto-shredding (deleting per-user encryption keys so write-once archive copies become unreadable).

Follow-up questions

  • How would you automatically attach a recurring company notice to newly created reservations without running manual batch jobs? Introduce a standing comment_rules(rule_id, org_id, supplier_id, starts_from, starts_to, text, active) table managed by org admins. Whenever a new reservation is confirmed or rebooked, the booking flow evaluates matching active rules and calls CommentService.update_comment (source = "rule"), recording (rule_id, reservation_id) in a comment_rule_applications table with a UNIQUE constraint inside the same transaction so subsequent itinerary edits never append the same rule twice. When an admin first creates a rule, trigger one standard batch job to backfill already-confirmed upcoming bookings in that window so past and future bookings stay consistent.
  • How would the data model evolve if travelers and support staff also needed multi-turn message threads on a booking? Keep aux_comments strictly as the single special-request string sent to external hotels and car suppliers, and add a separate append-only reservation_messages(message_id, reservation_id, author_id, visibility, body, created_at) table for multi-turn discussion (visibility distinguishing internal admin/support notes from traveler-visible replies). Separating the two prevents internal support chatter from accidentally syncing to a hotel front desk and avoids forcing downstream supplier integrations to guess how to flatten a chat thread into 500 characters.
  • What happens when two administrators kick off concurrent bulk jobs whose reservation filters partially overlap? Both jobs execute safely without deadlocks or corrupted history because every chunk locks rows in sorted reservation_id order (ORDER BY reservation_id). If both jobs are APPEND operations, the second worker on a shared reservation waits a few milliseconds for the first worker's chunk commit, reads the newly incremented version under SELECT ... FOR UPDATE, and appends its line cleanly below the first job's line (producing two distinct audit revisions). If either job is a SET or CLEAR with skip_if_changed = true, whichever job reaches a shared row second sees current.version != version_at_preview, skips that row cleanly, and surfaces the exact count of skipped overlaps in the admin's job summary.

Follow-up questions

Similar questions

More Navan interview questions

All 2 Navan questions →