Scaling Architecture to 10 Million Daily Active Users: Capacity, Caching, and LLM API Costs

    This article covers three problems that usually appear first when a system grows from one million to ten million daily active users: insufficient peak capacity, thread exhaustion caused by synchronous calls, and runaway large language model (LLM) API bills. It provides calculation methods, parameter ranges, and a checklist for each area. All figures are example assumptions and should be recalibrated with your own traffic data before launch.

    Key Takeaways

    At ten million daily active users, a system usually runs into three problems first: insufficient capacity at peak hours, thread exhaustion from synchronous calls, and LLM API bills that grow out of control. This article addresses each problem with calculation methods you can apply directly, parameter ranges, and a checklist. The figures are example assumptions. Recalibrate them with your own traffic data before launch.

    1. Where the System Breaks First at Ten Million DAU

    In a monolithic application, one slow module can occupy every thread in the process and take down other features with it. At ten million daily active users, these cascading failures happen more often, because peak-hour request volume far exceeds the daily average. The goal of the architecture changes is to contain failures to specific areas and leave the system enough headroom during peak hours.

    1.1 Use Capacity Watermarks to Decide When to Scale

    Estimate peak traffic before scaling, not just the daily average. A simple method:

    • Total daily requests = daily active users × average requests per user per day
    • Average QPS = total daily requests ÷ number of seconds in the peak period
    • Peak QPS = average QPS × peak factor (commonly 2 to 3)

    For example, with 10 million daily active users and 30 requests per user per day, total daily requests are 300 million. If that traffic is concentrated in 4 hours, the average QPS is about 20,800. With a peak factor of 3, the estimated peak is about 62,500 QPS.

    The recommended capacity watermark is to keep CPU utilization at 60% to 70% during normal peak periods. This leaves room for traffic bursts and single-machine failures.

    Key parameters for elastic scaling:

    • Scale-out metric: Set a CPU utilization target of around 60%, or use a custom metric based on the QPS limit per Pod.
    • Scale-in stabilization window: At least 5 minutes, so the replica count does not oscillate when traffic fluctuates.
    • Minimum replica count: Never scale to zero. Set the minimum based on historical traffic at the morning peak.
    • Scheduled scaling: Scale out 10 minutes before known morning peaks. Do not rely entirely on metric triggers, because new Pods need time to start and warm up.
    • Cold start: Pre-pull container images. After a service starts, warm up the local cache before routing traffic to it.

    Base load test conclusions on production traffic. Use traffic replay or shadow traffic, and record P99 latency, error rate, thread pool utilization, and database connection count. When P99 latency exceeds the target or thread pool utilization passes 80%, treat that as the capacity limit for the service.

    1.2 Make Non-Core Paths Asynchronous

    The problem with synchronous calls is that if a downstream service takes one extra second, the upstream thread is occupied for that same second. Logging, push notifications, and data statistics do not affect the result a user sees right away, so they can be moved to a message queue and processed asynchronously.

    This approach has two benefits. Response times for the API get shorter, and the message queue smooths out sudden traffic spikes, which protects the database from being overwhelmed. The cost is that messages may be delivered more than once, so consumers must be idempotent. A common method is to write each message’s unique ID to a deduplication table.

    Monitor message backlog, consumption latency, and consumption failure rate. Set alerts for backlog thresholds, because a growing backlog usually means consumers cannot keep up or a downstream dependency is already failing.

    1.3 Multi-Level Caching and Data Consistency

    Massive read traffic needs a cache to absorb it. A common design is a two-level structure: a local cache for extremely hot data with short expiration times, and a distributed cache for shared data.

    Caches introduce consistency problems. The common read-write strategy is Cache Aside:

    • On read, check the cache first. On a miss, query the database, then backfill the cache.
    • On update, update the database first, then delete the cache entry instead of updating it.

    Delayed double deletion is often used to handle dirty data caused by concurrent reads and writes. However, the delay must be longer than the primary-replica replication lag. Otherwise, a stale value may still be read. A more reliable approach is to listen to database change logs and let a message queue drive cache deletion, which achieves eventual consistency.

    Three common cache problems and their solutions:

    • Cache penetration: When queries target data that does not exist, cache empty results for a short time, and add a Bloom filter at the entry point.
    • Cache breakdown: When a hot key expires, a large number of requests hit the database at once. Rebuild the cache with a mutex lock, or use logical expiration for hot data.
    • Cache avalanche: When many keys expire at the same time, add random jitter to the TTL, for example a base value plus a random 0 to 300 seconds.

    2. LLM API Billing: Calculate Costs Before Optimizing

    LLM API costs depend on both the number of calls and the number of tokens. Pricing differs significantly between providers, so read each provider’s pricing rules before designing your system.

    2.1 Common Billing Methods Compared

    Billing method Billing unit Suitable scenarios Main risks
    Per-call Each call Simple tasks with fixed output length Unfair when request costs vary widely in length
    Per-token Input and output tokens Most generation tasks Costs rise with longer context, so conversation history length must be controlled
    Tiered pricing Unit price drops after usage passes a threshold Stable, large-scale workloads Requires usage forecasts, or usage may fall into the higher-priced tier
    Off-peak discount Lower unit price during specific hours Offline tasks that can tolerate delay Not suitable for real-time interaction

    Check the provider’s pricing page for current prices, since they change over time. Output tokens are usually priced higher than input tokens, so the cost of tasks that generate long text grows quickly.

    2.2 Cost Calculation Method

    The formula for the cost of a single call:

    Cost per call = input tokens × input unit price + output tokens × output unit price

    Here is a hypothetical example. Assume an input price of CNY 1 per million tokens and an output price of CNY 4 per million tokens. These are assumed values, not actual quotes. Suppose there are 1 million calls per day, with an average of 800 input tokens and 300 output tokens per call:

    • Input cost: 1 million × 800 = 800 million tokens, or 800 million tokens at CNY 1 per million, which is CNY 800.
    • Output cost: 1 million × 300 = 300 million tokens, or 300 million tokens at CNY 4 per million, which is CNY 1,200.
    • Daily total: CNY 2,000.

    When you calculate costs, state your assumptions: average token counts, call volume, unit prices, and model version. Without them, the numbers cannot be checked against actual usage during the next review.

    2.3 Semantic Caching

    Semantic caching intercepts repeated questions that have the same meaning but different wording. The method converts each question into a vector, compares it with the vectors of past questions, and returns the stored answer directly when similarity exceeds a threshold.

    Keep three points in mind:

    • Do not pick the similarity threshold arbitrarily. Test it on manually labeled question pairs, measure the false hit rate, and then choose the threshold.
    • Use a consistent definition of hit rate: Hit rate = number of cache hits ÷ total number of requests.
    • Requests that contain personal user information, real-time data, or session context should not enter the semantic cache. Otherwise, the cache may return wrong or outdated answers.

    2.4 Model Routing

    Not every request needs a large model. The routing layer selects the appropriate model for each request. Judging complexity by text length alone is unreliable, because a very long text may only require a simple format conversion. A better approach combines several features, such as task type, whether multi-step reasoning is needed, whether tools are called, and which business line the user belongs to.

    The following example can serve as a starting point. The weights and threshold are initial values and must be calibrated on an offline evaluation set:

    1. import json
    2. from dataclasses import dataclass
    3. @dataclass
    4. class RouteDecision:
    5. model: str
    6. score: float
    7. class ModelRouter:
    8. def __init__(self, small_client, large_client, threshold: float = 0.6):
    9. # threshold needs to be calibrated on an offline evaluation set; 0.6 is only a placeholder value
    10. self.small = small_client
    11. self.large = large_client
    12. self.threshold = threshold
    13. def score(self, req: dict) -> float:
    14. # Normalize each feature to the 0 to 1 range, then compute a weighted sum
    15. length = min(len(req["prompt"]) / 4000, 1.0)
    16. multi_step = 1.0 if req.get("needs_reasoning") else 0.0
    17. has_tools = 1.0 if req.get("tools") else 0.0
    18. return 0.4 * length + 0.4 * multi_step + 0.2 * has_tools
    19. def decide(self, req: dict) -> RouteDecision:
    20. s = self.score(req)
    21. model = "small" if s < self.threshold else "large"
    22. return RouteDecision(model=model, score=s)
    23. def call(self, req: dict) -> str:
    24. max_tokens = req.get("max_tokens", 512)
    25. decision = self.decide(req)
    26. if decision.model == "small":
    27. answer = self.small.generate(req["prompt"], max_tokens=max_tokens)
    28. # If the small model's output fails validation, escalate to the large model and retry
    29. if not self._passes_check(answer, req):
    30. answer = self.large.generate(req["prompt"], max_tokens=max_tokens)
    31. return answer
    32. return self.large.generate(req["prompt"], max_tokens=max_tokens)
    33. def _passes_check(self, answer: str, req: dict) -> bool:
    34. if not answer or not answer.strip():
    35. return False
    36. if req.get("expect_json"):
    37. try:
    38. json.loads(answer)
    39. except ValueError:
    40. return False
    41. return True

    Before you roll out the routing policy, run a small A/B test. For example, send 5% of traffic to the new router and compare three metrics: quality score, cost per 1,000 calls, and P95 latency. If quality drops beyond the agreed range, roll back the routing policy.

    The average cost after routing can be estimated as:

    Average cost = small model