Scalable REST and Streaming Randomness Platform

Hard · System Design · Software Engineer · Onsite

Prompt

Architect a multi-tenant backend platform that serves random values at high throughput across both request/response HTTP endpoints and long-lived streaming channels (for instance, delivering unpredictable one-time values, unbiased bounded integers in [1, 10], or deterministic random-access batches at (stream = 3, offset = 500000) for reproducible cluster simulations and auditable selections).

Scope & Expectations

  • Interfaces and versioning: Define synchronous REST and continuous streaming contracts, payload shapes, flow-control behavior, and versioning strategies for both wire schemas and generation algorithms.
  • Entropy, generator classes, and reproducibility: Explain how hardware and OS entropy are harvested, justify cryptographic (CSPRNG) versus statistical (PRNG) generator trade-offs, prevent range-mapping bias, and support deterministic seeded replay.
  • Tenancy, quotas, and abuse defense: Cover per-tenant rate limits and byte quotas, noisy-neighbor isolation, cryptographic hygiene, and anti-abuse safeguards.
  • Operations and SLAs: Detail secret-safe observability, container rollout and horizontal scaling practices, failure modes, and target latency and availability SLAs.

Step-by-step walkthrough

  1. Clarify scope: why call an API for random numbers?

    Begin with the question every experienced interviewer asks: every modern operating system already provides fast, cryptographically strong random bytes in microseconds via a local system call (getrandom() on Linux, secrets in Python). Why build a network service? Three real business needs justify it (especially at a regulated fintech platform running promotions, compliance audits, and risk simulations):

    1. Cross-language, multi-year reproducibility: Monte Carlo risk simulations, A/B experiment assignments, and backtests need the exact same numbers across Python, Go, and Java workers — and again six months later during an audit. Standard library generators differ across languages and library upgrades.
    2. Tamper-evident audited draws: Sweepstakes, member giveaways, and regulatory compliance sampling ("select 1% of last month's wire transfers for review") require cryptographic proof of when a draw occurred, over which committed list, and that nobody secretly re-rolled until they liked the winner.
    3. One vetted implementation of tricky range math: Unbiased integer mapping, uniform [0, 1) floats, and k-of-n sampling without replacement are notoriously easy to get subtly wrong across hundreds of microservices.

    Explicit non-goal: Long-lived cryptographic keys (TLS private keys, database encryption keys) must never be fetched over this API because raw secret bytes would traverse network proxies and pod RAM; callers generate those locally or inside a KMS (Key Management Service) (a hardware-backed service that generates and uses encryption keys without exposing them).

    Functional requirements

    • Output types: raw bytes, integers in [min, max], uniform floats in [0, 1), UUIDv4, k-of-n distinct sample indices, and (server-seeded mode) standard normal floats.
    • Three operating modes:
      • secure: unpredictable output from a CSPRNG (cryptographically secure pseudorandom number generator), stateless, never logged or stored.
      • seeded: deterministic, random-access sequence keyed by (algorithm_version, seed, stream, offset).
      • audited draw: a secure or seeded draw persisted to an append-only tamper-evident ledger before returning a signed receipt.
    • Transports: HTTP POST REST for request/response batches; gRPC and chunked HTTP streaming for continuous high-throughput consumers.
    • Multi-tenancy: ~300 internal services and ~20 external partner tenants with isolated quotas and blast-radius boundaries.

    Non-functional requirements

    • Fail closed: Never fall back to a weak generator on entropy or self-test errors — return 503 Service Unavailable.
    • Immutability: Once published, a versioned seeded algorithm (blake2b-ctr@1) never alters a single output bit.
    • Zero output leakage: Random outputs and plaintext seeds never appear in logs, metrics, traces, or crash dumps.
    • Latency & availability: Secure REST server-side p99 < 10 ms (99% of calls under 10 milliseconds) and 99.99% monthly availability (~4.3 min/month downtime budget).
  2. Back-of-the-envelope numbers

    Workload assumptions
      Tenants                     ~300 internal services + ~20 external partners
      REST peak QPS               50,000 req/s (median payload 256 B, p99 payload 8 KiB, max 64 KiB)
      REST throughput             50,000 * 256 B = ~12.8 MB/s typical
      Concurrent streams          500 active streams; 0.2 MB/s typical, capped at 4 MB/s per stream
      Stream throughput           500 * 0.2 MB/s = 100 MB/s typical; 500 * 4 MB/s = 2 GB/s ceiling
      Audited draws               50,000/day (~0.6/s avg, bursts to 50/s when campaigns close)
    
    CPU & network sizing
      CSPRNG generation speed     ChaCha20 / AES-CTR produces >= 1 GB/s per CPU core -> even 2 GB/s
                                  takes ~2-3 cores fleet-wide! CPU goes to TLS, auth, and JSON.
      REST pods per region        ~5,000 req/s per pod within p99 < 10 ms -> 10 pods needed at peak;
                                  deploy 15 pods across 3 AZs (survives 1 AZ loss) in each of 2 regions
      Stream pods per region      NIC-bound (10 Gbps NIC = ~1.25 GB/s) -> 6 pods across 3 AZs per region
    
    Durable storage
      Secure mode outputs         0 bytes (never persisted!)
      Seeded sequence metadata    100,000 active sequences * ~1 KB = ~100 MB
      Audited draw ledger         50,000/day * ~2 KB = ~100 MB/day = ~37 GB/year (~260 GB over 7 years)
    

    Takeaway: Storage (< 300 GB over 7 years) and raw bit-generation CPU are tiny. The hard engineering challenges are unbiased cryptographic generation without state-cloning bugs, stateless random-access reproducibility, multi-tenant amplification defense, and 99.99% hot-path availability.

  3. API contracts and dual-axis versioning

    1. Secure mode (stateless REST)

    POST /v1/random/bytes        {"length": 32, "encoding": "base64"}
    POST /v1/random/integers     {"count": 5, "min": 1, "max": 10, "unique": false}
    POST /v1/random/floats       {"count": 1000}
    POST /v1/random/uuids        {"count": 10}
    POST /v1/random/sample       {"population": 62500, "k": 50}
    
    200 OK   Cache-Control: no-store
             {"request_id": "req_4b9c...", "mode": "secure", "values": [8, 1, 10, 4, 8]}
    400      INVALID_RANGE | COUNT_TOO_LARGE | UNIQUE_EXCEEDS_SPAN
    429      QUOTA_EXCEEDED   (Retry-After: 2)
    503      GENERATOR_UNAVAILABLE
    

    2. Seeded reproducible sequences

    POST /v1/sequences
         {"algorithm": "blake2b-ctr@1", "seed_b64": "<optional 32B>", "revealable": false, "label": "sim-q1"}
    201  {"sequence_id": "seq_73d...", "algorithm": "blake2b-ctr@1", "seed_sha256": "8e1c..."}
    
    POST /v1/sequences/{sequence_id}/draw
         {"stream": 3, "offset": 500000, "count": 250, "type": "integers", "min": 1, "max": 10}
    200  {"values": [...], "offset": 500000, "next_offset": 500250}
    
    POST /v1/sequences/{sequence_id}/reveal     # Allowed ONLY when revealable=true AFTER an audited draw
    200  {"seed_b64": "..."}
    

    3. Audited draws & streaming

    POST /v1/draws    Idempotency-Key: 91a4-3ef0...   (mandatory header)
         {"purpose": "wire-audit-2026-q1", "type": "sample", "population": 62500, "k": 50,
          "source": {"mode": "seeded", "sequence_id": "seq_73d...", "stream": 0, "offset": 0,
                     "entrants_sha256": "f02b..."}}
    201  {"draw_id": "drw_...", "values": [...], "recorded_at": "2026-03-31T18:00:00Z",
          "receipt": {"record_hash": "...", "signature": "...", "key_id": "draw-sign-2026"}}
    
    gRPC RandomService.Stream(StreamRequest{mode, type, min, max, chunk_size, max_bytes_per_s,
                                            sequence_id?, stream?, start_offset?})
         -> stream Chunk{offset, next_offset, values}
    

    Key API contract decisions: - Always POST with Cache-Control: no-store, never GET: HTTP GET responses can be cached by corporate proxies or CDNs, which would catastrophically hand identical "random" numbers to two callers. - Per-mode retry rules: Retrying a secure call simply draws fresh values. Seeded /draw is naturally idempotent (same offset always yields the same output). Audited /draws requires an idempotency key (a caller token mapped to the committed ledger row) so network retries return the original draw instead of giving the caller a free re-roll. - Two independent version axes: 1. HTTP/gRPC contract version (/v1, /v2): additive fields stay in /v1; breaking schema changes ship as /v2 with a 12-month overlap and RFC 8594 Deprecation / Sunset headers. 2. Pinned algorithm version (blake2b-ctr@1): stored immutably on each sequence_id. Even an internal optimization that flips 1 bit ships as blake2b-ctr@2 so @1 sequences reproduce forever.

  4. Data model and what must never be stored

    tenants       tenant_id PK, tier (standard | critical), allowed_modes,
                  quotas {req_per_s, bytes_per_s, bytes_per_day, max_streams, max_batch}, status
    credentials   credential_id PK, tenant_id, auth_type (mtls_spiffe | api_key_sha256),
                  scopes, ip_allowlist, expires_at
    sequences     sequence_id PK (128-bit random), tenant_id, algorithm ("blake2b-ctr@1"),
                  wrapped_seed (encrypted via KMS envelope key), seed_sha256, revealable,
                  created_at, expires_at
    draws         draw_id PK, tenant_id, UNIQUE (tenant_id, idempotency_key), purpose,
    (append-only) request_json, source_json, values_json, recorded_at,
                  prev_hash, record_hash, kms_receipt_sig
    usage_minute  tenant_id, minute_bucket, endpoint, req_count, output_bytes, throttled_count
    
    • Zero persistence for secure outputs: Values exist only in the outgoing socket buffer.
    • Envelope-encrypted seeds: Anyone with a sequence's seed can predict all future draws, so seed is encrypted via KMS (wrapped_seed) before touching PostgreSQL and never returned again (except via one-time /reveal after a commit-reveal sweepstakes draw).
    • Cross-region durable ledger: tenants, credentials, sequences, and draws live in a small PostgreSQL cluster (primary in Region A + 1 local-AZ standby in Region A + 2 standbys in Region B, configured with synchronous_standby_names = 'ANY 2 (...)'). Every committed audited draw lands in both regions before returning 201, while secure REST calls never touch PostgreSQL at all.
  5. High-level architecture

         Internal Services (mTLS)                 External Partners (TLS 1.3 + API Key)
                    |                                              |
                    v                                              v
       +----------------------------------------------------------------------------+
       | Regional L7 API Gateway (Active-Active in Region A & Region B)             |
       | - Auth + cached tenant config (30 s refresh)                               |
       | - Local token buckets (req/s, output bytes/s) + per-tenant concurrency cap |
       +---------------------+------------------------------------+-----------------+
                             | REST                               | gRPC / HTTP Stream
                             v                                    v
       +-------------------------------------+    +---------------------------------+
       | rng-api Pods (stateless, CPU-scaled)|    | rng-stream Pods (NIC-scaled)    |
       | - Secure: OS getrandom() + unbiased |    | - Per-stream ChaCha20 / PRF     |
       | - Seeded: BLAKE2b-CTR + LRU key RAM |    | - HTTP/2 window backpressure    |
       | - Startup KAT + 1-min clone canary  |    | - Redis 30 s stream leases      |
       +----+--------------+-------------+---+    +---------------+-----------------+
            |              |             |                        |
       Linux Kernel     KMS (unwrap   PostgreSQL Ledger        Regional Redis
       CSPRNG           wrapped_seed  (sequences + draws,      (1 s batched daily
       (getrandom <-    on cache miss) sync 2-of-3 standbys)    byte quota + leases)
        CPU RDRAND +                         |
        virtio-rng)                  Daily KMS-signed hash -> WORM Object Storage
    
       Isolation: "critical" tier tenants (e.g., auth/OTP services) run in a dedicated cell
       (separate gateway pool + separate rng-api pods) so standard bursts never affect them.
    
  6. Deep dive 1: hardware entropy, cryptographic generators, and unbiased math

    1. Entropy stack and CSPRNG vs. PRNG: - Entropy is physical unpredictability harvested from hardware events (CPU thermal noise via RDRAND/RDSEED, interrupt timings, and host passthrough via virtio-rng inside virtual machines). - A statistical PRNG (pseudorandom number generator) like Mersenne Twister (MT19937) is fast and evenly distributed, but observing just 624 consecutive 32-bit outputs lets an attacker reconstruct its entire internal array and predict every future number. A CSPRNG (like Linux's ChaCha20 kernel pool or NIST SP 800-90A AES-CTR DRBG) guarantees that observing gigabytes of output gives zero computational advantage in predicting the next bit. - Architectural choice: Never deploy a non-cryptographic PRNG on any security-adjacent path. On rng-api REST pods (~12.8 MB/s across 15 pods, < 1 MB/s per pod), read directly from the Linux kernel CSPRNG via getrandom() (secrets in Python): it takes < 2 microseconds for 256 bytes, never blocks once booted, and automatically reseeds on VM live-clone events via the hypervisor VM Generation ID. On rng-stream pods (2 GB/s), run one per-thread user-space ChaCha20 CSPRNG seeded with 32 bytes from getrandom(), rekeying every 1 MiB or 60 s and verifying os.getpid() before each block so fork() never duplicates a stream.

    2. Eliminating modulo bias and float rounding bugs: - Modulo bias: If you map one random byte (0..255, 256 outcomes) onto [1, 10] (span = 10) via 1 + (byte % 10), 256 = 10 * 25 + 6, so remainders 0..5 appear 26 times while 6..9 appear only 25 times (4% relative skew!). Fix this with rejection sampling — discard values in the incomplete tail (>= 250) and redraw so every outcome 1..10 has exact 25 / 250 = 1/10 probability. - Uniform floats in [0, 1): Draw 53 random bits (matching IEEE-754 double significand precision) and multiply by 2^-53. Never compute uint64 / 2^64: values near 2^64 - 1 round up to 1.0, violating [0, 1) and breaking callers that compute log(1.0 - u)!

    import secrets
    from typing import List
    
    
    def secure_integers(count: int, low: int, high: int) -> List[int]:
        span = high - low + 1
        if span <= 0:
            raise ValueError("high must be >= low")
        results: List[int] = []
        for _ in range(count):
            # secrets.randbelow uses OS getrandom() + rejection sampling (zero modulo bias)
            offset = secrets.randbelow(span)
            results.append(low + offset)
        return results
    

    3. Continuous health checks & VM-clone canary (failing closed): - Startup Known-Answer Tests (KAT): Verify deterministic test vectors and a getrandom() read before marking Kubernetes readiness healthy. - Dedicated fleet clone canary: Each pod initializes a separate in-memory canary generator from getrandom() at boot and emits one 128-bit canary token per minute to an internal collector (never served to users). Why separate from the serving generator? Two pods restored from the same frozen VM snapshot serve different user traffic sizes, so sampling their serving streams once a minute lands at different offsets and misses the clone! A dedicated canary steps in lockstep once a minute, immediately catching identical state. Across 10^9 total canary tokens (~38 years of fleet operation), accidental collision probability by the birthday bound is (10^9)^2 / 2^129 ≈ 1.5 * 10^-21 — so a single match proves cloned RNG state and pages security while draining both pods (503).

  7. Deep dive 2: counter-based seeding, reproducibility, and commit-reveal

    Why stateful PRNGs fail distributed reproducibility: Seeding MT19937 or PCG in memory means jumping to offset = 500,000 requires stepping forward half a million times (O(N)), parallel workers collide unless given tricky jump-ahead polynomials, and retrying a failed network chunk requires sticky server state.

    Solution — stateless counter-based PRF (blake2b-ctr@1): Model the sequence as a pure mathematical function value = F(key, kind, stream, index, attempt) using a PRF (pseudorandom function) — here, keyed BLAKE2b-128, available in Python's hashlib, Go, Rust, and libsodium:

    import hashlib
    import struct
    
    TWO_64 = 2 ** 64
    KIND_INT = 1
    KIND_FLOAT = 2
    
    
    def derive_sequence_key(seed: bytes, context: bytes = b"") -> bytes:
        # Derives a 32-byte PRF key; optional context mixes in entrants_sha256 for fair draws
        hasher = hashlib.blake2b(seed, digest_size=32, person=b"rng-seq-v1")
        if context:
            hasher.update(context)
        return hasher.digest()
    
    
    def prf_u64(key: bytes, kind: int, stream: int, index: int, attempt: int) -> int:
        # Pack coordinates unambiguously in big-endian: 1B kind, 4B stream, 8B index, 4B attempt
        coord_bytes = struct.pack(">BIQI", kind, stream, index, attempt)
        digest = hashlib.blake2b(coord_bytes, key=key, digest_size=16).digest()
        return int.from_bytes(digest[:8], byteorder="big")
    
    
    def seeded_int(key: bytes, stream: int, index: int, low: int, high: int) -> int:
        span = high - low + 1                         # Supports 1 <= span <= 2**64
        usable_ceiling = (TWO_64 // span) * span      # Largest multiple of span <= 2**64
        attempt = 0
        while True:
            word = prf_u64(key, KIND_INT, stream, index, attempt)
            if word < usable_ceiling:
                return low + (word % span)
            # Retry increments attempt at the SAME index so index+1 never shifts!
            attempt += 1
    
    
    def seeded_float(key: bytes, stream: int, index: int) -> float:
        word = prf_u64(key, KIND_FLOAT, stream, index, 0)
        # Shift right 11 bits to keep top 53 bits, then scale onto exact [0.0, 1.0) grid
        return (word >> 11) * (2.0 ** -53)
    

    Why this construction hits every subtle edge case: - Rejection retries never shift later offsets: Incrementing attempt inside (kind, stream, index, attempt) keeps index 1-to-1 with output position, so offset = 500,000 is computed in O(1) time and next_offset is always offset + count. - Bounded worst-case loop: Rejected fraction is (2^64 mod span) / 2^64. For span <= 2^32, retry probability is < 2^-32; even at the adversarial worst case span = 2^63 + 1, 2^64 mod span = 2^63 - 1, so retry probability is strictly < 0.5 (< 2 attempts expected!). - Cross-language bit-exactness + CI golden vectors: Integers and uniform floats use only integer operations and exact power-of-two scaling (2^-53), avoiding sin/cos/log where libm implementations differ in the last bit (normal@1 deviates are documented as server-computed). Every SDK and CI build validates thousands of frozen golden test vectors so accidental drift fails the build immediately. - Commit-then-reveal for provably fair sweepstakes: Before entries close, the promotion team creates a revealable: true sequence with a service-generated seed and publicly posts seed_sha256. Once entries close, they run an audited draw passing entrants_sha256 (mixed via derive_sequence_key), and only after that draw commits in draws does /reveal unlock seed_b64 so anyone can verify SHA256(seed) == seed_sha256 and recompute the winners!

  8. Deep dive 3: byte-aware quotas, tenant bulkheads, and abuse defense

    1. Byte-aware rate limiting (defending the 650x amplification vector): A tiny 100-byte JSON request asking for 64 KiB of random bytes amplifies bandwidth ~650x. Limiting requests/s alone is insufficient — enforce both req/s and output_bytes/s, plus bytes/day and max_streams: - Hot-path rates (req/s, bytes/s): Local in-memory token buckets (counters refilling at limit / num_gateways per second) inside each L7 gateway pod — 0 ms network overhead. - Daily byte quota (bytes/day): Each gateway batches tenant byte counts to regional Redis once every 1 s (INCRBY quota:{tenant}:{yyyy-mm-dd} delta_bytes) and caches whether the tenant is exhausted. Worst-case overshoot across G gateways is at most ~2 seconds of the tenant's bytes/s rate — tiny for billing/abuse protection while keeping Redis off the per-request path. - Streaming backpressure & leases: rng-stream generates the next 64 KiB chunk only when the client's HTTP/2 or gRPC flow-control window has space, bounding per-stream RAM to ~64 KiB against slow-loris readers. Active stream caps use a 30 s Redis lease renewed every 10 s so crashed pods auto-release slots.

    2. Multi-tenant isolation & tamper-evident audit defense: - Cell & bulkhead isolation: Critical internal tenants (e.g., login challenge nonces) route to an isolated critical cell (dedicated gateway + rng-api pods). Within shared standard pods, per-tenant concurrency is capped at 25% of worker slots, and long-lived streams live on separate rng-stream pods so they never starve short REST calls. - Tenant data scoping: sequence_id and draw_id are unguessable 128-bit IDs; querying another tenant's ID returns 404 Not Found (never 403, avoiding existence leaks). Core dumps are disabled (ulimit -c 0) so crash files never write unwrapped seed keys to disk. - Anti-reroll ledger integrity: Every draws row computes record_hash = SHA256(canonical_row || prev_hash) before returning 201, alerts security if one tenant submits multiple distinct idempotency keys for the same purpose, and anchors a daily KMS-signed root hash into WORM (write-once-read-many) object storage (cloud buckets locked against deletion or modification even by root admins).

  9. Scaling, safe deployment, and per-mode SLAs

    • Horizontal & multi-region scaling: Two active-active regions (Region A and Region B), each provisioned to carry 100% of peak traffic if the other goes dark. secure mode is 100% stateless; seeded mode caches unwrapped 32-byte sequence_keys in pod LRU memory (10 min TTL) so > 99.9% of seeded draws avoid both PostgreSQL and KMS hops; audited draws write through Region A's primary (~50k/day is < 1 txn/s average, keeping the hash chain strictly linear).
    • Safe rollout & container hygiene: Never bake RNG state into container images or initialize user-space generators prior to fork(). Deploy one region at a time (1 canary pod -> 5% -> 25% -> 100%), gating promotion on startup KATs, golden vectors, 5xx rate, and p99 latency.
    Server-side SLAs (measured at regional gateway)
      Mode / Endpoint                  Latency SLA                          Monthly Availability
      -------------------------------  -----------------------------------  --------------------
      Secure REST (<= 4 KiB)           p50 < 2 ms,  p99 < 10 ms             99.99% (~4.3 min/mo)
      Seeded REST (warm key cache)     p50 < 3 ms,  p99 < 20 ms             99.95% (~21.6 min/mo)
      Seeded REST (cold KMS unwrap)                 p99 < 60 ms             99.95%
      Audited draw (cross-region DB)                p99 < 200 ms            99.90% (~43.2 min/mo)
      Streaming (gRPC / HTTP)          1st chunk p99 < 50 ms; >= 99% rate   99.95%
    

    Notice why audited draw deliberately carries a looser SLA (99.90%, p99 < 200 ms): it performs a synchronous cross-region PostgreSQL commit so an audited result can never be returned without being durably recorded.

  10. Failure handling, observability, and trade-off summary

    Failure Scenario                Caller Impact                   Automated System Response
    ------------------------------  ------------------------------  ------------------------------------------------
    Pod fails KAT / RNG self-test   None (retried on healthy pod)   Pod returns 503, drops readiness, pages on-call
    Canary detects cloned RNG state None if caught on 1st minute    Page security immediately, quarantine both pods
    KMS regional outage             Cold seeded keys return 503     Warm cached keys & all secure calls unaffected
    PostgreSQL primary failover     Audited draws 503 (~15-30 s)    Promote synced standby; client retries idem_key
    Redis quota cluster down        None                            Gateways enforce local rate + fallback daily cap
    Entire Region A outage          Brief reconnect (< 10 s)        Anycast shifts traffic to Region B; promote B DB
    
    • Observability without secret leakage: Track request rate, 429/503 rates, latency histograms, bytes generated, rejection-sampling retry ratio (verifying it matches theoretical (2^64 mod span) / 2^64), KMS cache hit rate, and hourly offline statistical sanity suites (PractRand / NIST SP 800-22 on unserved test streams to catch buffer-plumbing regressions). Enforce a CI redaction test that injects sentinel outputs and fails the build if any byte appears in logs or OpenTelemetry spans.
    • Core trade-offs summarized: Direct getrandom() over user-space caching on REST for zero fork/snapshot risk; 503 fail-closed over silent PRNG fallback; counter-based PRF over stateful PRNGs for O(1) random access; immutable @version algorithms over in-place edits; and synchronous ledger commits over availability on audited draws.

Intuition & how it works

Think of a network randomness platform like three specialized stations behind one secure counter — a sealed casino card shoe (secure), a numbered reference book of random tables (seeded), and a televised lottery machine with a notary public (audited draw). When an app needs an unpredictable one-time token (secure), the server pulls fresh randomness straight from the operating system's CSPRNG (cryptographically secure pseudorandom number generator) — an engine mixed from hardware entropy (physical CPU noise and interrupt timings) whose next bit cannot be predicted even after seeing gigabytes of prior output — and forgets the numbers immediately. When data scientists run a simulation across 200 workers (seeded), they look up page stream and line offset in a deterministic PRF (pseudorandom function) — a keyed cryptographic hash F(key, stream, index) that computes line 500,000 directly in one step without reading lines 0..499,999. And when a regulated audit or promotion picks winners (audited draw), the notary writes the input and result into a hash-chained ledger before handing over a signed receipt so nobody can secretly re-roll.

Why do naive designs fail? Serving random values from a fast statistical PRNG (pseudorandom number generator) like Mersenne Twister (MT19937) lets anyone who observes 624 outputs reconstruct its internal memory and predict every future draw, while exposing GET endpoints lets HTTP proxies cache and hand the exact same "random" response to multiple callers. Mapping random bytes onto [1, 10] with 1 + (byte % 10) introduces modulo bias (because 256 = 10 * 25 + 6, making 1..6 show up more often than 7..10), and stepping a stateful seeded generator forward sequentially makes random access or stateless retries impossible at scale.

Trace three concrete mini-examples showing how each subtle piece works:

1. Unbiased [1, 10] draw via rejection sampling (toy 1-byte example: 0..255 -> 1..10, span = 10):
   - Largest multiple of 10 <= 256 is 250 (valid range: 0..249; remainder tail: 250..255).
   - Draw byte = 253 -> >= 250 (in biased tail), REJECT and redraw!
   - Draw byte = 47  -> < 250, ACCEPT: 1 + (47 % 10) = 8 (exact 25/250 = 1/10 probability each).

2. O(1) random access in seeded sequence "blake2b-ctr@1" at (stream=3, offset=500_000):
   - Pod computes BLAKE2b(key, pack(kind=INT, stream=3, index=500_000, attempt=0)).
   - If the 64-bit word hits the tiny rejection tail, retry with attempt=1 at the SAME index=500_000
     so index=500_001 never shifts! Returns values and next_offset = 500_001.

3. Tamper-evident audited compliance draw (Idempotency-Key = "wire-audit-q1"):
   - Server draws sample -> commits row + SHA256(row || prev_hash) to cross-region Postgres ->
     signs receipt -> returns 201. A client retry with "wire-audit-q1" gets the exact recorded sample.

Key trade-offs

  • Network RNG service vs. local OS getrandom(). Local OS generation is faster (< 2 microseconds), has zero network outage risk, and keeps long-lived encryption keys off the wire — so encryption keys stay local or in KMS (Key Management Service). The network API exists specifically for cross-language multi-year reproducibility, notarized audited draws, and a single vetted implementation of unbiased range/sampling math.
  • Direct kernel getrandom() vs. user-space DRBG on REST pods. Calling getrandom() per REST request (~1 MB/s per pod) avoids user-space fork() and VM-snapshot state-duplication bugs completely; per-thread user-space ChaCha20 generators (with pid checks and frequent rekeying) are reserved for 2 GB/s streaming pods where kernel syscall throughput actually matters.
  • Fail closed (503) vs. degrading to a fallback PRNG. Returning 503 when a startup KAT (known-answer test) or continuous health check fails costs a sliver of availability, whereas falling back to a weak generator hides the outage while silently serving predictable outputs.
  • Counter-based PRF (F(key, stream, index, attempt)) vs. stateful sequential PRNG. Paying one BLAKE2b hash per coordinate buys O(1) jump-to-offset, millions of non-overlapping parallel streams, and completely stateless retries across pods, trading away a small constant factor in raw single-core CPU speed.
  • Immutable @version algorithms vs. upgrading math in place. Freezing blake2b-ctr@1 forever (enforced by CI golden test vectors) guarantees a simulation from three years ago reproduces bit-for-bit, at the cost of maintaining old algorithm code paths until every @1 sequence expires.
  • Local gateway token buckets + 1-second Redis batching vs. synchronous central quotas. Enforcing req/s and output_bytes/s locally in gateway RAM keeps hot-path latency under 10 ms p99 with zero Redis hop per request, trading a tiny bounded daily-quota overshoot (<= 2 s of a tenant's allowed byte rate).
  • Synchronous cross-region ledger write on audited draw vs. high availability. Committing to primary + cross-region standby before returning 201 lowers the audited endpoint's SLA (99.90%, p99 < 200 ms) in exchange for guaranteeing a caller can never see a draw that could be lost in a regional disaster and re-rolled.

Common mistakes

  • Using HTTP GET without Cache-Control: no-store, allowing CDNs, browser caches, or reverse proxies to replay one random payload to multiple callers.
  • Modulo bias (rand64 % span) and float 1.0 overflow (rand64 / 2^64), which skew non-power-of-two integer ranges and occasionally round 2^64 - 1 up to 1.0 outside [0, 1).
  • Using MT19937, xorshift, or java.util.Random for unpredictable tokens, letting an observer recover internal state and predict future outputs.
  • Initializing a user-space RNG inside a Docker image build, pre-fork master process, or VM snapshot without pid and clone-canary checks, causing multiple containers to emit identical "random" sequences.
  • Advancing index on rejection-sampling retries in seeded mode, which makes value[500,000] depend on how many retries occurred in 0..499,999 and destroys O(1) random access!
  • Relying on NIST SP 800-22 or PractRand statistical suites to prove cryptographic security — statistical suites catch plumbing bugs (all-zero buffers, truncated bytes), but a predictable linear congruential or Mersenne generator passes many statistical tests while remaining insecure.
  • Rate-limiting only requests/s while ignoring output_bytes/s, leaving a 650x amplification hole where tiny requests saturate NICs with 64 KiB responses.
  • Logging full request/response bodies in tracing middleware, leaking secret tokens and plaintext seeds into centralized log indexes.

Follow-up questions

  • How can an external auditor verify that a promotional or compliance draw was not secretly re-rolled by the operator? Use a commit-then-reveal protocol combined with the hash-chained ledger: before entries close, the operator creates a revealable: true sequence with a service-generated seed (encrypted in KMS so the operator never sees it) and publishes seed_sha256. After entries close, the operator publishes entrants_sha256 (the SHA-256 of the sorted candidate list) and calls POST /v1/draws with both sequence_id and entrants_sha256 mixed into derive_sequence_key, committing the result to the ledger (anchored daily to WORM write-once storage) before /reveal unlocks the raw seed. Anyone can verify SHA256(seed) == seed_sha256 and rerun the open blake2b-ctr@1 reference script to confirm the exact same winners — and if zero trust in the platform operator itself is required, mix in the next pulse from a public randomness beacon (such as League of Entropy drand) scheduled for a timestamp after entries close.
  • When a quantitative team needs 100 GB of seeded floats across 200 simulation workers, should they pull from the streaming endpoint or generate locally, and why? Generate locally via the shared SDK rather than streaming over the network: pulling 100 GB over TLS at a 4 MB/s per-stream quota takes nearly 7 hours (100,000 MB / 4 MB/s = 25,000 s) and burns egress bandwidth to move deterministic math. Instead, the team registers one sequence_id in the service to record seed_sha256, blake2b-ctr@1, and run metadata for auditability, while their 200 workers evaluate the local SDK on stream = 0 .. 199 at > 500 MB/s per core with bit-identical results verified by shared CI golden vectors (reserving network streaming for genuine secure CSPRNG consumers or thin clients).
  • Why does VM-snapshot clone detection require a dedicated canary generator rather than sampling the live serving stream, and how do you ship a new seeded algorithm without breaking older runs? Two pods restored from the same paused VM snapshot immediately serve slightly different traffic rates (say 4,200 vs. 3,910 requests in minute one), so sampling their serving generators at t = 60 s compares offset 4,201 against 3,911 and misses the clone even though 3,910 callers received duplicate numbers; a dedicated canary generator advances only once per minute in lockstep, colliding on tick 1. For algorithm upgrades, treat seeded engines as immutable append-only plugins keyed by sequences.algorithm: ship a faster engine under a new tag such as chacha12-ctr@2 with its own frozen golden vectors, make @2 the default for new sequences, and keep blake2b-ctr@1 active until every @1 sequence passes expires_at.

Follow-up questions

Similar questions

More SoFi interview questions

All 17 SoFi questions →