From MaaS to TaaS: Key Architectural Practices for Token Services

    As large language models become mainstream, the way AI services are delivered is shifting from Model-as-a-Service (MaaS) to Token-as-a-Service (TaaS), where usage is metered and billed per token. This article explains why tokens became the unit of billing, outlines the roles of the four types of market participants, and breaks down the core architectural challenges of building a high-concurrency, low-latency TaaS platform—including KV cache management and inference scheduling, streaming gateway design with rate limiting and metering, and distributed inference optimization. It also covers common mistakes in metering and rate limiting, evaluation metrics such as TTFT and TPOT, and future trends in metering standardization and full-stack co-optimization.

    With the widespread adoption of large language models, the way AI services are delivered is changing. In the past, enterprises primarily purchased model capability—Model as a Service (MaaS). Today, more and more services are metered and priced by the token—Token as a Service (TaaS). This article explains, from a developer’s perspective, why this shift is happening and breaks down the architectural concerns involved in building a high-concurrency, low-latency TaaS foundation.

    1. Why Tokens Became the Billing Unit

    A token is the smallest unit of text that a large model processes. Depending on the tokenizer, it can be a character, a word, or a subword fragment. When processing input and generating output, the model first maps tokens to vectors, then predicts the next token one at a time. Token count therefore maps directly to three categories of resource consumption: compute, GPU memory, and network transfer. Billing by token is essentially a way of quantifying these three costs.

    The cost structure of input and output is not the same. Input tokens are processed all at once at the start of a request—a phase commonly called prefill. Output tokens must be generated one by one, with each step depending on all previous results. As a result, per-token latency is usually higher in the output phase, and most of the waiting users perceive comes from there. Many pricing plans set different rates for input and output tokens precisely because of this difference.

    Regarding market size, published figures on token call volume vary widely, mostly because of differences in measurement methodology. Some statistics count only input tokens; others count both input and output. Some count requests; others count tokens. Some cover the entire market; others rely on samples. Before citing any volume figure, you should verify these methodologies and judge whether the numbers are actually comparable. This article does not cite specific volumes and only describes the trend: scenarios such as intelligent customer service, code assistance, enterprise knowledge-base Q&A, and office automation are all steadily increasing their calls to model inference.

    2. The Roles of Four Types of Participants

    The token service market is built jointly by several types of players, each responsible for a different layer.

    1. Cloud providers offer GPU clusters, distributed storage, and containerized orchestration platforms, packaging compute into standardized APIs. Enterprises can access inference capability without building their own data centers, which significantly lowers the barrier to entry.
    2. Model companies handle foundation model R&D, continuously releasing versions with larger parameter counts and stronger multimodal capabilities. Some also provide token generation services directly, using their own or partner compute resources.
    3. Telecom operators leverage backbone networks and edge computing nodes to handle end-to-end data transmission. Their focus includes reducing network latency, ensuring stable streaming delivery, and deploying lightweight models at the edge to shorten response paths.
    4. AI infrastructure companies specialize in hardware-software co-optimization, covering AI chips, high-performance inference frameworks, and customized communication libraries. The goal of this work is to ease bottlenecks caused by GPU memory capacity and communication bandwidth, improving token throughput per GPU and per cluster.

    For developers, this division of labor means you need to be clear about which layer your system sits in. When self-hosting inference services, you must handle compute scheduling, metering, and the gateway all at once. When only calling third-party APIs, you focus more on rate limiting, retries, and cost control.

    3. Three Core Architectural Challenges of TaaS

    The move from MaaS to TaaS is not just a business model change—the technical architecture needs to be redesigned as well. A provider must maintain stable output under high concurrency while achieving token-level precise metering. The following three areas are where difficulties most commonly arise.

    3.1 GPU Memory Management and Inference Scheduling

    In LLM inference, the KV cache is the main source of GPU memory consumption. Each request must store the key-value vectors of its historical tokens during generation; the longer the request and the higher the concurrency, the larger the footprint. If you pre-allocate contiguous memory per request based on the maximum length, fragmentation easily occurs, eventually triggering OOM (Out of Memory) errors during traffic peaks.

    Modern inference frameworks commonly adopt block-based management similar to PagedAttention: the KV cache is split into fixed-size blocks allocated on demand, much like virtual memory paging in an operating system. This improves memory utilization and allows a single GPU to hold more concurrent requests.

    The benefits of this mechanism have boundaries. It is most valuable for long-context workloads and scenarios where many requests share a common prefix; for workloads dominated by short requests, the gains are relatively limited. When troubleshooting memory issues, you can check in the following order:

    • Whether max_new_tokens is set too high, causing each request to reserve too much memory;
    • Whether block utilization and fragmentation rates are consistently high;
    • Whether the batch size matches the memory headroom, and whether peak concurrency exceeds expectations;
    • Whether long-tail requests are occupying memory for extended periods and blocking other requests.

    3.2 Elastic Fault Tolerance and Streaming Gateway Design

    TaaS services typically push tokens incrementally in a streaming fashion to reduce time to first token. The gateway needs to support long-lived connections and SSE (Server-Sent Events), and must handle scaling and rate limiting during traffic spikes. Below is a piece of teaching pseudocode illustrating the basic ideas of rate limiting and metering. It is not a production implementation and has not been load-tested. The recommended environment is Python 3.10 or later with FastAPI and uvicorn; refer to the official documentation for specific versions. engine_stream and count_input_tokens must be replaced with a real inference engine interface and tokenizer.

    1. import time
    2. from collections import defaultdict, deque
    3. from fastapi import FastAPI, HTTPException, Request
    4. from fastapi.responses import StreamingResponse
    5. app = FastAPI()
    6. WINDOW_SECONDS = 1.0
    7. MAX_TOKENS_PER_WINDOW = 10_000
    8. MAX_NEW_TOKENS_LIMIT = 4096
    9. class TokenMeter:
    10. """Tracks per-user token usage within a sliding window.
    11. No locking is needed within a single process: asyncio runs on a single
    12. thread, and there is no await between the check and the write.
    13. For multi-process deployments, switch to shared storage such as Redis
    14. and use a Lua script to guarantee atomicity."""
    15. def __init__(self):
    16. self._windows = defaultdict(deque) # user_id -> deque of [timestamp, tokens]
    17. def reserve(self, user_id: str, tokens: int):
    18. now = time.monotonic()
    19. window = self._windows[user_id]
    20. while window and now - window[0][0] > WINDOW_SECONDS:
    21. window.popleft()
    22. if sum(entry[1] for entry in window) + tokens > MAX_TOKENS_PER_WINDOW:
    23. return None
    24. entry = [now, tokens]
    25. window.append(entry)
    26. return entry
    27. @staticmethod
    28. def settle(entry, actual_tokens: int):
    29. # Settle against actual usage when the request ends or disconnects;
    30. # passing 0 rolls back the entire reservation
    31. entry[1] = actual_tokens
    32. meter = TokenMeter()
    33. async def engine_stream(prompt: str, max_new_tokens: int):
    34. # Placeholder: replace with the inference engine's streaming interface,
    35. # yielding a batch of newly generated output tokens each time
    36. yield []
    37. def count_input_tokens(prompt: str) -> int:
    38. # Placeholder: should count with the same tokenizer as the target model
    39. return len(prompt)
    40. def sse_data(text: str) -> str:
    41. # In SSE every line must start with "data: "; newlines inside the text
    42. # need to be split into separate lines
    43. return "".join(f"data: {line}\n" for line in text.split("\n")) + "\n"
    44. async def sse_events(request: Request, entry, input_tokens: int,
    45. prompt: str, max_new_tokens: int):
    46. output_tokens = 0
    47. try:
    48. async for batch in engine_stream(prompt, max_new_tokens):
    49. if await request.is_disconnected():
    50. break
    51. output_tokens += len(batch)
    52. yield sse_data("".join(batch))
    53. yield "data: [DONE]\n\n"
    54. except Exception:
    55. yield 'event: error\ndata: {"code": "upstream_error", "retryable": true}\n\n'
    56. finally:
    57. meter.settle(entry, input_tokens + output_tokens)
    58. @app.post("/v1/taas/generate")
    59. async def generate(request: Request):
    60. body = await request.json()
    61. user_id = body.get("user_id")
    62. prompt = body.get("prompt")
    63. if not user_id or not prompt:
    64. raise HTTPException(status_code=400, detail="user_id and prompt are required")
    65. max_new_tokens = min(int(body.get("max_new_tokens", 512)), MAX_NEW_TOKENS_LIMIT)
    66. input_tokens = count_input_tokens(prompt)
    67. # Reserve quota as "input + max output" before the request starts;
    68. # return 429 immediately if the limit is exceeded, without entering streaming
    69. entry = meter.reserve(user_id, input_tokens + max_new_tokens)
    70. if entry is None:
    71. raise HTTPException(status_code=429, detail="rate limit exceeded",
    72. headers={"Retry-After": "1"})
    73. return StreamingResponse(
    74. sse_events(request, entry, input_tokens, prompt, max_new_tokens),
    75. media_type="text/event-stream",
    76. headers={"Cache-Control": "no-cache"},
    77. )

    Three points about this code deserve attention. First, input tokens are metered once at request start, while output tokens accumulate batch by batch in the stream; the two are tracked separately. Second, quota is reserved upfront and settled afterward. If the client disconnects or the upstream errors out, the already-generated portion is metered as-is, and the reservation for the ungenerated portion is rolled back at settlement. Third, requests that exceed the limit return 429 before streaming begins, rather than inserting an error event mid-stream—this lets the client correctly recognize rate limiting and back off before retrying.

    A production environment also needs the following additions:

    • Heartbeats: Streaming output may go silent for a long time if upstream inference slows down, and proxy layers tend to drop connections on idle timeouts. Sending a comment frame (e.g., : ping) roughly every 15 seconds keeps the connection alive.
    • Parameter validation: The int(...) call in the example throws on invalid input; production code needs unified parameter validation and error responses.
    • Error code semantics: 400 indicates a parameter error and should not be retried; 429 and 503 indicate temporary unavailability and can be retried with exponential backoff plus random jitter, respecting the Retry-After header. Once a stream has started producing output, the request must not be replayed in full, or you will double-bill and produce duplicate content. Resumable streaming or idempotent retries require the client to carry a request ID, with server-side cooperation.

    3.3 Distributed Inference and Communication Optimization

    Once a model’s parameters exceed the memory capacity of a single GPU, tensor parallelism and pipeline parallelism become necessary. Tensor parallelism requires frequent All-Reduce communication across GPUs, and communication latency directly affects the generation time of every token. Common optimizations include overlapping computation with communication, using high-speed interconnects (such as InfiniBand), and tuning All-Reduce at the algorithm and topology levels.

    When evaluating such optimizations, you must use consistent metrics and testing methodology; otherwise, different approaches cannot be compared. Common metrics include:

    • Throughput: the number of tokens generated per unit of time (tokens/s);
    • TTFT (Time To First Token): the time from request to the first returned token, which primarily affects perceived startup speed;
    • TPOT (Time Per Output Token): the average time to generate each output token, which primarily affects the smoothness of streaming output.

    During testing, fix the input length, output length, and concurrency; warm up before sampling; and report percentiles such as P50, P95, and P99. Looking only at averages easily hides tail-latency problems.

    4. Architecture Selection and Common Mistakes

    Most selection decisions come down to a few questions. Whether the model fits on a single GPU determines whether tensor parallelism is needed. Whether the business is latency-sensitive or throughput-sensitive determines the direction for batch size: larger batches usually mean higher throughput, but the TTFT of individual requests may degrade. Long contexts significantly increase KV cache usage and should be accounted for separately in capacity planning.

    Common mistakes in practice include:

    • Admitting requests first and deducting quota afterward, which leads to overselling under high concurrency;
    • Using character counts instead of token counts for metering, so billing does not match the model’s actual consumption;
    • Failing to settle after a mid-stream disconnection, causing under-metering or quota being occupied indefinitely;
    • Rate-limit windows that never roll with time, leaving users wrongly throttled or entirely unthrottled;
    • Multiple processes each maintaining their own counters, effectively multiplying the total quota—shared storage with atomic updates is required;
    • Monitoring only average latency while ignoring changes in TTFT and P99.

    5. Looking Ahead: Metering Standardization and Full-Stack Co-Optimization

    As the token service market grows, AI capability will increasingly be consumed by volume, like water and electricity. In the near term, two directions are worth watching.

    The first is standardization of metering and interfaces. The same piece of text tokenizes differently across models, and billing granularity varies as well. Unified metering conventions and common API specifications would reduce migration costs and make it easier for the application layer to switch between providers. This direction is likely to move forward, but concrete progress depends on negotiation among industry players.

    The second is full-stack co-optimization. From chip instruction sets, operator libraries, and inference frameworks up to application logic, optimization at every layer affects the final cost. Some cloud providers have begun pursuing integrated solutions spanning compute, models, and applications, aiming to reduce losses between hardware and software. Developers can look for optimization headroom at their own layer and share latency and cost metrics with upstream and downstream teams.

    Understanding how token services are metered and what architectural constraints they face helps you estimate application costs more accurately—and helps you account for the interplay between GPU memory, networking, and billing at design time.