Building a Custom AI Service Gateway: Architecture and Compliance Practices
This article explores the architecture and compliance practices for building a custom AI service gateway. It defines the boundaries of authorized upstream channels, introduces a four-layer architecture model encompassing access, routing, billing, and observability, and explains unified authentication with multi-tenant isolation. The article also provides pseudocode demonstrating the request lifecycle, from authentication to quota settlement.
1. Defining Boundaries: Only Official and Authorized Channels
Building a custom access layer allows for unified management of multiple vendor calls, provided that every upstream channel is legitimate. This article only discusses three types of channels: official vendor APIs, vendor-authorized interfaces, and enterprise self-hosted private models.
The following practices are out of scope and should never appear in any implementation:
- Purchasing, renting, or sharing accounts from others, or using finished accounts as a resource pool.
- Bypassing platform risk controls by switching IPs, spoofing browser fingerprints, or rotating devices.
- Scraping or reverse-engineering vendor web interfaces to use them as APIs.
- Exploiting regional differences or payment vulnerabilities to bypass vendor geographical restrictions and Terms of Service.
These practices typically violate Terms of Service and can lead to account bans, frozen funds, and data leaks, with no support provided by the vendor. They should be excluded from the design phase entirely.
2. Overall Architecture: A Four-Layer Model
A maintainable access layer is generally divided into four layers:
- Access Layer: Receives application requests, performs identity authentication and authorization, and supports both standard and streaming (SSE) interfaces.
- Routing and Scheduling Layer: Selects upstream vendors based on model type, priority, and cost budget, while handling retries and circuit breaking.
- Subscription and Billing Layer: Manages plans, quotas, balances, and cost accounting.
- Observability and Audit Layer: Records request logs, latency, error codes, and costs, supporting alerting and reconciliation.
The gateway service runs on cloud servers or container clusters. All upstream keys are stored only on the gateway side, such as in environment variables or a Key Management Service (KMS). Users only hold exclusive keys issued by the gateway.
The pseudocode below illustrates the sequence of a gateway processing a request. Authentication precedes quota checks, and quota checks precede forwarding. Quotas are reserved before the request, released upon failure, and settled based on actual usage upon success; therefore, failed requests are not charged.
def handle_request(request):key = extract_key(request)if key is None:return error(401, "missing_key")user = authenticate(key) # Compare hashes, check if status is activeif user is None:return error(401, "invalid_key")if not rate_limiter.allow(key.id): # Token bucket rate limitingreturn error(429, "rate_limited")estimate = estimate_tokens(request)reservation = quota_service.reserve(user, request.model, estimate)if reservation is None:return error(429, "quota_exceeded")provider = router.select(user, request.model)if provider is None:quota_service.release(reservation)return error(503, "no_available_provider")try:response = call_with_retry(provider, request, timeout=30, max_retries=1)except ProviderError as e:quota_service.release(reservation)record_usage(user, provider, request.model, status="error", error_code=e.code)return error(502, "upstream_error")quota_service.settle(reservation, response.usage.total_tokens)record_usage(user, provider, request.model, response.usage, status="ok")return response
3. Unified Authentication and Multi-tenant Isolation
The gateway stores only the hash value of the key; the plaintext is returned only once at creation. Redis can organize data according to the table below:
| Redis Key | Type | Content | Expiration Policy |
|---|---|---|---|
| key:{key_hash} | Hash | user_id, plan, status | No expiration, update status when revoked |
| quota:{user_id}:{yy |
