Building Access Control and Immutable Audit Systems
System DesignModel answerLast updated
Design a low-latency authorization framework and tamper-proof audit logging infrastructure for a high-throughput financial application.
You're architecting the security layer for a financial services platform that processes large volumes of transactions. The system needs robust access control and comprehensive audit trails to meet regulatory requirements.
Core Requirements
Access Control System:
- Implement both role-based (RBAC) and attribute-based (ABAC) policies to handle complex rules like "analysts can view portfolios only within their assigned territories and only during business hours"
- Authorization decisions must add minimal overhead since they're evaluated on every API call
- The system must remain secure during partial outages—critical operations should fail safely if authorization state is uncertain
Audit Trail System:
- Record every authorization decision (approved and rejected) plus all data-modifying operations
- Logs must be append-only and verifiable against tampering
- Support both real-time monitoring for security alerts and historical queries spanning multiple years for compliance reviews
Traffic Characteristics
- Authorization checks: 50,000 per second during peak periods
- Audit retention requirement: 7 years minimum
What to Cover
- Overall system architecture with key components
- How authorization decisions are evaluated efficiently
- Caching strategies and how to invalidate stale permissions when roles or policies change
- Storage architecture for audit data that balances query speed against long-term cost
Hints
Hint 1
Authorization latency is critical—consider where policy evaluation happens relative to application servers
Hint 2
Audit logs grow indefinitely but access patterns vary by age—think about tiering
Hint 3
Tamper-evidence requires cryptographic structures that link records together
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Access Control and Audit Architecture
Understanding Scale and Constraints
First, quantify the problem precisely:
- Authorization throughput: 50k requests/sec, but many requests need multiple checks (read account and place order). Plan for 100-150k authorization evaluations per second.
- Latency target: Adding more than 1ms p99 makes the system feel slow. Round-tripping to a remote authorization service on every request won't work.
- Availability model: Financial operations fail closed—if we can't verify permission, deny the action. Some read-only queries might tolerate slightly stale decisions.
- Audit data volume: If we log ~1KB per decision at 15k sustained RPS, that's roughly 1.3 billion events daily, or 1.3TB raw. Columnar compression (Parquet) typically achieves 5-7x reduction, bringing it to ~200GB/day. Over seven years: approximately 500TB compressed.
- Regulatory needs: Write-once storage with tamper detection. Investigators need recent data searchable within seconds, historical data queryable in minutes.
Architecture Overview
Request Flow:
Client → API Gateway (authentication, JWT validation)
→ Application Service
├─ Business logic container
└─ Authorization sidecar (co-located)
├─ Policy engine with compiled rules (in-memory)
├─ Attribute cache (user roles, territories, metadata)
└─ Audit event buffer (disk-backed queue)
Control Plane (out of request path):
Policy Management Service (version-controlled, peer-reviewed)
→ Policy Distribution Service (pushes to sidecars via streaming RPC)
Attribute Source (user directory, account database)
→ Change Data Capture → Distribution Service
Audit Pipeline:
Sidecar buffers → Kafka (replicated, persistent)
→ Integrity Service (builds hash chains, signs Merkle roots)
→ Hot tier: Elasticsearch (last 60 days, full-text indexed)
→ Warm tier: Parquet files on object storage (2 years, SQL-queryable)
→ Cold tier: Glacier with retention locks (7 years)
→ Real-time: Stream processor for anomaly detection and alerting
Merkle roots → Separate append-only ledger
The critical design choice: policy evaluation runs locally in a sidecar, not via network call. The central control plane distributes policies but never sits in the critical path. If distribution fails, sidecars continue with their last-known-good policy version.
Authorization API Design
POST /authorize
{
"principal": {
"id": "user_847",
"type": "analyst",
"session": "sess_19x"
},
"operation": "portfolio.view",
"target": {
"type": "portfolio",
"id": "port_332",
"properties": {"territory": "EMEA"}
},
"environment": {
"timestamp": "2025-01-15T09:30:00Z",
"source_ip": "10.0.5.18",
"mfa_verified": true
}
}
Response:
{
"allowed": true,
"decision_id": "dec_a8f3c",
"policy_version": 1847,
"matched_rules": ["role:analyst", "attribute:territory_match", "attribute:business_hours"],
"constraints": ["redact_ssn"],
"cache_duration_ms": 3000
}
Include a batch evaluation endpoint for list views ("which of these 200 portfolios am I allowed to see?"). The engine evaluates role membership first (fast), then attribute conditions. For example: has_role(analyst) AND target.territory IN principal.territories AND is_business_hours(environment.timestamp).
Every decision returns its unique ID and policy version, making it reproducible during investigations.
Caching Strategy
Three cache layers with different invalidation semantics:
1. Policy cache (in-memory, sidecar)
- Policies compile to bytecode and load into memory, tagged with monotonic version numbers
- Distribution service maintains long-lived connections and pushes incremental updates
- Each sidecar reports which version it's running; monitoring tracks propagation lag
2. Attribute cache (in-memory, sidecar)
- Stores role assignments, territory mappings, account ownership
- Source database changes flow through CDC pipeline → Kafka → distributors → sidecars
- Each attribute set has an
attribute_versionthat increments on change
3. Decision cache (optional, very short TTL)
- Key:
hash(principal, operation, target, policy_version, attribute_version) - Because versions are in the cache key, updates automatically invalidate old entries
- TTL capped at next time boundary—a "business hours" decision expires at 5:00 PM regardless of nominal TTL
- Typically 1-5 seconds to handle request bursts for identical decisions
Staleness handling: If a sidecar hasn't received a heartbeat from the distributor within its staleness window (e.g., 10 seconds), it marks itself degraded and denies all mutations while continuing to serve reads. This prevents silent policy violations during outages.
Emergency revocations: Terminating an employee's access uses a high-priority revocation list evaluated before all other rules. Revocations propagate immediately through a dedicated channel and bypass batching.
Audit Logging Implementation
Capture mechanism:
- Authorization decisions: Emitted asynchronously to a local persistent queue, then forwarded to Kafka. Request processing never blocks on logging.
- Data mutations: Use the transactional outbox pattern. The audit record is written in the same database transaction as the business operation. A separate relay process reads the outbox table and publishes to Kafka. No audit record = no commit.
Tamper-evidence architecture:
- An integrity service reads Kafka partitions sequentially. For each event:
event.hash = SHA256(previous_hash || serialize(event)) - Every minute, build a Merkle tree over that minute's hashes and sign the root with an HSM-backed key managed by a separate security team
- Signed roots are written to an append-only store in an isolated cloud account
- Optionally anchor roots to an external timestamping authority for third-party verification
- A daily verification job recomputes chains and Merkle roots. Any alteration or deletion breaks the chain at a detectable point. Merkle proofs allow verifying individual events without replaying the entire log.
- Cloud object storage with compliance-mode retention locks prevents deletion even by administrators until retention expires
Storage tiers:
| Tier | Technology | Retention | Query Performance | Cost/TB/mo |
|---|---|---|---|---|
| Hot | Elasticsearch | 60 days | Milliseconds, full-text | $$$$ |
| Warm | Parquet on S3 + Trino | 2 years | Seconds, SQL | $$ |
| Cold | Glacier Deep Archive + locks | 7 years | Hours (retrieval) | $ |
Keeping 500TB in Elasticsearch would cost hundreds of thousands monthly. Glacier costs a few thousand. The warm tier handles most compliance queries at reasonable cost while maintaining good performance.
Key Trade-offs
Sidecar vs. centralized service:
- Sidecars provide sub-millisecond latency and survive network partitions
- Cost: higher memory footprint per pod and more complex policy distribution
- Mitigation: For the hottest services, use a linked library instead of a separate process
Synchronous vs. asynchronous audit logging:
- Async protects latency for read-heavy workloads
- Critical mutations use the outbox pattern to guarantee audit records exist before commits
- Trade-off: slight additional database write overhead for the outbox table
Attribute caching vs. always-fresh lookups:
- Caching enables local evaluation but risks stale role assignments
- Bounded staleness (seconds) is acceptable for most access decisions
- Emergency revocations bypass the cache through a separate fast path
Hot vs. warm vs. cold storage:
- Hot tier enables real-time forensics but becomes prohibitively expensive at scale
- Most queries happen on recent data; historical access is rare but required
- Accepting minutes-to-hours retrieval time for old data reduces costs by orders of magnitude
Common Mistakes
- Putting authorization on the network critical path without caching
- Not versioning policies and attributes, making decision cache invalidation unreliable
- Logging audit events fire-and-forget without delivery guarantees for critical operations
- Storing all audit data in a single system optimized for either cost or performance but not tiered appropriately
- Implementing hash chains without regular Merkle tree aggregation, making verification computationally expensive
- Failing to handle control plane outages gracefully (sidecars should degrade, not fail open)