Caching Strategy
Server-Side Cache
- 30-second TTL on all paid endpoints
- Identical requests within 30s = FREE (same wallet, same URL, same params)
- Cache key: wallet_address + endpoint + query_params
- Cache header: X-Cache: HIT or X-Cache: MISS
Client-Side Caching
In-Memory Cache (Python)
import time
class CachedClient:
def __init__(self, api_client, ttl=30):
self.api = api_client
self.ttl = ttl
self.cache = {}
def get(self, url):
now = time.time()
if url in self.cache:
age = now - self.cache[url]['time']
if age < self.ttl:
return self.cache[url]['data']
data = self.api.get(url).json()
self.cache[url] = {'data': data, 'time': now}
return data
Redis Cache (Production)
import redis
import json
cache = redis.Redis(host='localhost', port=6379, db=0)
def get_price(symbol):
key = f"foursec:price:{symbol}"
cached = cache.get(key)
if cached:
return json.loads(cached)
data = client.get(f"https://api.foursec.xyz/price/{symbol}").json()
cache.setex(key, 28, json.dumps(data)) # 28s (under 30s server cache)
return data
Multi-Layer Cache
Layer 1: In-memory (TTL: 10s) - fastest, single process
Layer 2: Redis (TTL: 25s) - shared across processes
Layer 3: Server cache (TTL: 30s) - free after payment
Cache Invalidation
When to Bypass Cache
- Trading execution (need freshest data)
- Arbitrage detection (stale data = lost profit)
When to Use Cache
- Dashboard display (30s delay acceptable)
- Portfolio valuation (1-minute accuracy fine)
- Historical analysis (data doesn't change)
Cost Optimization
| Strategy | Savings | Best For |
|---|---|---|
| 30s server cache | 50-70% | All use cases |
| 60s client cache | 80% | Dashboards, trackers |
| 5min client cache | 95% | Research, analytics |
| Batch + cache | 90% | Multi-token queries |
TIP
Combine client-side caching (60s) with server cache (30s) for maximum savings. First request pays, next 2 are free.