04 - Cache Architecture

Overview

OpenAlgo implements a multi-layer caching system to achieve high performance with 100,000+ trading symbols. The caching architecture minimizes database queries, reduces latency, and ensures fast API responses during high-frequency trading operations.

Cache Architecture Diagram

Cache Types

1. Symbol Cache (BrokerSymbolCache)

High-performance in-memory cache for 100,000+ trading symbols.

Location: database/token_db_enhanced.py

Features:

  • O(1) lookups via multiple indexes

  • ~50MB memory for 100K symbols

  • Session-based TTL (resets at 3:00 AM IST)

  • Cache statistics tracking

Cache Population:

Lookup Example:

2. Authentication Caches

Location: database/auth_db.py

Session-Based TTL Calculation:

3. API Key Caches

Three-Level API Key Verification:

Implementation:

Cache Lifecycle

1. Startup Restoration

On application startup, caches are restored from database:

2. Login Population

After successful broker authentication:

Cache Hook:

3. Logout Cleanup

On logout, caches are cleared:

Cache Statistics & Health

Statistics Tracking

Health Monitoring

Cache Configuration

Environment Variables

TTL Summary

Cache
TTL
Purpose

auth_cache

Until session expiry

Auth token storage

feed_token_cache

Until session expiry

WebSocket feed tokens

broker_cache

50 minutes

Broker name lookups

verified_api_key_cache

10 hours

Valid API key user IDs

invalid_api_key_cache

5 minutes

Failed API key attempts

symbol_cache

Until session expiry

Trading symbols

Performance Characteristics

Memory Usage

Component
Size
Memory

Symbol Cache (100K symbols)

~500 bytes/symbol

~50 MB

Auth Cache (1024 entries)

~1 KB/entry

~1 MB

API Key Cache (1024 entries)

~100 bytes/entry

~100 KB

Total

~52 MB

Lookup Performance

Operation
Complexity
Latency

Symbol lookup (cached)

O(1)

<1 ms

Auth token lookup (cached)

O(1)

<1 ms

API key verification (cached)

O(1)

<1 ms

API key verification (DB)

O(1) + Argon2

~100 ms

Symbol lookup (DB fallback)

O(log n)

~5 ms

Cache Invalidation

Automatic Invalidation

  1. TTL Expiry - Caches auto-expire based on TTL

  2. Session Expiry - Symbol and auth caches reset at 3:00 AM IST

  3. Logout - All user-specific caches cleared

Manual Invalidation

Key Files Reference

File
Purpose

database/token_db_enhanced.py

Symbol cache implementation

database/auth_db.py

Auth and API key caches

database/cache_restoration.py

Startup cache restoration

database/master_contract_cache_hook.py

Cache lifecycle hooks

Best Practices

  1. Always check cache first - Use cache methods before DB queries

  2. Invalidate on mutation - Clear relevant cache entries on data changes

  3. Monitor hit rates - Investigate if hit rate drops below 90%

  4. Respect TTLs - Don't manually extend cache entries

  5. Handle cache misses gracefully - Fall back to DB on miss

Last updated