3/10
Technical Architecture & AI Engineering · 7 min read

System Design: Multi-Tenant Webhook Ingestion and SOC 2 Compliance Audit Pipeline

Architect a 5,000-events/sec webhook ingestion platform with sub-30ms edge capture, S3 Object Lock WORM retention, idempotent rule evaluation, and tenant isolation.

Why This Matters at Engineering Leadership Scale

Compliance platforms ingest continuous webhooks from GitHub, Jira, Okta, and CI pipelines to prove controls like "every production PR had peer review." Dropping webhooks during database maintenance breaks customer SOC 2 audits, while upstream providers time out after 3 to 5 seconds and retry aggressively during deployment bursts.

Engineering leaders must separate fast, lossless edge capture from downstream compliance rule evaluation, isolate noisy-neighbor CI storms, guarantee idempotent findings, and retain tamper-proof 7-year audit archives affordably.

Core Mental Model & Architecture

Anchor capacity and 7-year retention math upfront:

  • Throughput Math: 1,000 enterprise tenants, 5,000 events/sec peak (~1,500 avg = ~130M events/day).
  • WORM Archive Math: At ~2 KB/payload, raw intake is 260 GB/day (~95 TB/year raw). Zstd/gzip (~4x) reduces this to ~24 TB/year (~168 TB over 7 years). Batching into S3 Object Lock (COMPLIANCE mode) tiered to Glacier keeps 7-year storage near $2,500 to $4,000/month.
  • Normalized Findings Math: ~15% of webhooks emit findings (~20M rows/day * 400 bytes = 8 GB/day). Monthly partitioned Postgres tables keep 90 days hot (~720 GB) with older partitions exported to S3 Parquet.
ChoiceOption AOption B (Chosen)Rationale
Webhook HTTP ModeSync rule eval (200 OK)HMAC check + durable enqueue (202 Accepted <30ms)Prevents upstream timeouts and DB ops dropping events
7-Year Immutability7 years JSON in PostgresS3 Object Lock (WORM) 60s Zstd micro-batchesRegulator-grade immutability at 1/20th cost, low PUT fees
Queue IsolationGlobal FIFO queueKafka / SQS FIFO partitioned by tenant_idKeeps tenant ordering without cross-tenant starvation
Alert DispatchDB write then Slack callAtomic finding + alert_outbox TXZero lost compliance alerts on worker crash

Step-by-Step Implementation Tutorial

1. Decouple Edge Capture From Rule Evaluation

Give edge receivers zero Postgres dependency so DB failovers never drop customer webhooks.

text
EDGE (Stateless, <30ms p95, Zero Postgres Dependency):
GitHub/Jira/Okta -> API Gateway (Per-Tenant Rate Limit) -> Receiver:
  1. Constant-time HMAC-SHA256 check (dual-secret rotation)
  2. SHA-256 digest -> Multi-AZ Kafka (`partition_key = tenant_id`) -> HTTP 202 Accepted

CONSUMERS:
  [Archive]: Kafka Connect S3 Sink -> 60s Zstd micro-batches -> S3 Object Lock (WORM 7yr)
  [Rules]: Dedup (Redis + Postgres UNIQUE) -> Policy Rules -> Atomic TX (findings + alert_outbox)
           Poison (>4 retries) -> Per-Tenant DLQ + PagerDuty

2. Define the Idempotent Audit and Outbox Schema

Enforce strict uniqueness at the database layer so retries never inflate compliance violation counts.

sql
CREATE TABLE webhook_dedup (
  tenant_id          UUID NOT NULL,
  provider           TEXT NOT NULL,
  external_event_id  TEXT NOT NULL, -- e.g. X-GitHub-Delivery
  s3_worm_batch_uri  TEXT NOT NULL,
  received_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (tenant_id, provider, external_event_id)
);

CREATE TABLE compliance_findings (
  finding_id         UUID NOT NULL,
  tenant_id          UUID NOT NULL,
  control_code       TEXT NOT NULL, -- e.g. 'SOC2-CC8.1-PEER-REVIEW'
  status             TEXT NOT NULL CHECK (status IN ('PASS', 'FAIL')),
  evidence_s3_uri    TEXT NOT NULL,
  evaluated_at       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (tenant_id, evaluated_at, finding_id)
) PARTITION BY RANGE (evaluated_at);

CREATE TABLE alert_outbox (
  outbox_id          UUID PRIMARY KEY,
  tenant_id          UUID NOT NULL,
  finding_id         UUID NOT NULL,
  payload            JSONB NOT NULL,
  published_at       TIMESTAMPTZ
);

3. Handle the Minute-25 Curveball: 50,000 Duplicate Flood + 7-Year Regulator Export

"One enterprise customer's broken CI script blasts 50,000 duplicate webhooks in 30 seconds, while another needs a cryptographically verifiable 7-year audit export."

  1. 50,000 Duplicate Flood: Edge per-tenant token buckets throttle excess bursts above burst caps (429 Retry-After). Inside the consumer pool, Redis L1 SET NX backed by Postgres PRIMARY KEY(tenant_id, provider, external_event_id) drops duplicates in <2ms, while tenant_id partitioning isolates the storm completely from the other 999 customers.
  2. 7-Year Regulator Export: Because Kafka Connect seals 60-second Zstd bundles per tenant into S3 Object Lock (COMPLIANCE mode, immutable even to AWS root) under s3://audit-worm/{tenant_id}/, an async export job queries that prefix via Athena/S3 Batch and delivers a SHA-256 signed evidence archive in minutes.

4. Split Multi-Squad Ownership

  • Ingestion & Storage Squad (6 engineers): Owns edge rate limiting, HMAC verification, Kafka partitioning, S3 Object Lock WORM batching, and DLQ replay tooling.
  • Compliance Engine Squad (6 engineers): Owns SOC 2 / CPS 234 rule evaluation, partitioned Postgres findings, Transactional Outbox alerts, and auditor export portals.

Worked Production Scenario: Before vs. After

A B2B compliance SaaS serving 400 clients originally ran webhook rules synchronously against Postgres. Deployment waves pushed latency past GitHub's 10s timeout, causing dropped audit deliveries and duplicate findings on retries. Switching to stateless 202 Accepted edge capture, Kafka micro-batched S3 WORM archiving, tenant-partitioned queues, and unique-key idempotency stabilized the entire pipeline.

MetricBefore (Sync Webhook Handler)After (Decoupled Edge + WORM + Queue)Net Impact
Webhook Edge p95 Latency4.8s (frequent 504s)24ms (202 Accepted)200x faster ack
Dropped Audit Events / Quarter~1,200 during spikes/deploys0 (buffered across DB ops)100% audit completeness
Duplicate Findings Rate3.4% on retries0% (Redis + SQL unique key)Clean audit metrics
7-Year Retention Storage Cost$14,000/mo projected RDS$2,800/mo S3 Object Lock-80% retention TCO

Common Failure Modes & Anti-Patterns

1. Individual S3 PUTs Per Webhook Event

The trap: Writing 130M individual 2 KB files directly to S3 daily incurs ~$19,500/month in S3 PUT request fees alone. The structural fix: Persist synchronously to multi-AZ Kafka at the edge and use a Kafka Connect S3 Sink to write 50 MB Zstd micro-batches every 60 seconds into S3 Object Lock (cutting PUT costs 99.9%).

2. Breaking In-Flight Webhooks During Secret Rotation

The trap: Overwriting a tenant's HMAC secret immediately causes in-flight webhooks to fail 401 and drop. The structural fix: Support dual-secret validation (primary + secondary) with a 24-hour overlap window during rotation.

3. Letting One Poison Payload Stall a Tenant's Partition

The trap: An uncaught JSON parse exception retries infinitely inside a FIFO group, halting compliance monitoring for that customer. The structural fix: Cap retries (maxReceiveCount = 4), shunt malformed payloads to a per-tenant DLQ with immediate alerting, and keep healthy events moving.

How to Handle Pushback in the Room

Principal Engineer: "Writing every 2 KB webhook straight to S3 at 130M events/day burns $19,500/month in S3 PUT fees. How do you fix that?"

Calm Executive Response: "Spot on - individual PUTs do not scale financially at 130M/day. Our edge receiver writes synchronously to multi-AZ Kafka (returning 202 in under 15ms), and Kafka Connect micro-batches payloads into 50 MB Zstd objects per tenant every 60 seconds into S3 Object Lock, cutting PUT fees by 99.9% while maintaining full WORM durability."

Compliance Auditor: "If events sit in Kafka for 60 seconds before S3 Object Lock, how do you prove nothing was tampered with in transit?"

Calm Executive Response: "At the ingestion edge we immediately compute a SHA-256 digest of the raw HTTP body and provider HMAC headers, sealing that digest into the signed Kafka envelope. The S3 Sink verifies every digest before committing the WORM bundle, giving an unbroken cryptographic chain of custody."

Key Takeaways & This Week's Action Rep

  • Return 202 Accepted in <30ms: Verify HMAC, durably enqueue to multi-AZ Kafka, and decouple rule evaluation from HTTP intake.
  • Micro-batch into S3 Object Lock: Achieve 7-year WORM compliance without per-event S3 PUT fee explosions.
  • Layer duplicate and flood defenses: Combine edge per-tenant throttles, tenant_id partitioning, and UNIQUE(tenant_id, provider, external_event_id) constraints.
  • Use Transactional Outbox for compliance alerts: Persist findings and outbound alerts atomically.
  • This Week's Action Rep: Audit your main webhook receiver: measure p95 response time, verify whether a 5-minute Postgres outage drops webhooks, and confirm how it behaves under a 10x duplicate replay test.