Implementing Tenant-Aware Authorization & Rate Limiting in AI Microservices
Securing shared LLM gateways with API key scoping, sliding window token buckets, and vector collection multi-tenancy.
Core Takeaway
When multiple consumer applications share a centralized AI gateway, you cannot treat all callers as a single trusted client. Without strict tenant scoping, one misconfigured app can exhaust shared LLM quotas, leak vector embeddings to unauthorized users, or inflate infrastructure bills. This note details tenant-aware security for AI backends.
Problem Statement & Context
Shared backend services often fall into the trap of using a single global API key for upstream LLM calls. If client app 'A' deploys a runaway loop, client apps 'B' and 'C' immediately suffer 429 quota exhaustion. Furthermore, in RAG pipelines, failing to partition vector similarity searches by tenant creates serious data isolation risks.
Architectural Concepts & Implementation
1. Scoping Authentication via Hashed Service API Keys
Issue unique API keys per client application (app_id). Store only the SHA-256 hash of the API key in the database with defined capabilities (allowed models, max token budgets, permitted vector collection namespaces).
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import * as crypto from 'crypto';
@Injectable()
export class TenantAuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const apiKey = request.headers['x-api-key'];
if (!apiKey || typeof apiKey !== 'string') {
throw new UnauthorizedException('Missing x-api-key header');
}
const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex');
const tenant = await this.tenantRepo.findByKeyHash(keyHash);
if (!tenant || !tenant.isActive) {
throw new UnauthorizedException('Invalid or inactive API key');
}
// Attach verified tenant metadata to request context
request.tenant = {
id: tenant.id,
applicationId: tenant.applicationId,
allowedModels: tenant.allowedModels,
monthlyTokenBudget: tenant.monthlyTokenBudget,
};
return true;
}
}2. Tenant-Specific Sliding Window Rate Limiting in Redis
Protect against noisy neighbors by enforcing per-tenant request limits using Redis sliding window log algorithms. Calculate both request rate (requests per minute) and token consumption rate (estimated tokens per minute).
3. Enforcing Hard Pre-Filters in Vector Databases
In Qdrant and other vector engines, never retrieve top-k documents and then filter by tenant in application code. Always apply metadata pre-filtering inside the vector query itself to prevent cross-tenant data leakage.
export async function searchTenantVectorStore(
client: QdrantClient,
collectionName: string,
vector: number[],
tenantId: string,
limit = 5
) {
// Pre-filter enforces tenant isolation at the vector index level
return await client.search(collectionName, {
vector,
limit,
filter: {
must: [
{
key: 'tenantId',
match: { value: tenantId },
},
],
},
with_payload: true,
});
}Common Pitfalls & Trade-offs
- !Pitfall: Post-filtering vector queries. If tenant B's documents have higher raw similarity than tenant A's, doing post-retrieval filtering can result in zero returned documents for tenant A even though matching documents exist in the database.
- !Trade-off: Unified vector collections vs separate collections per tenant. Shared collections with metadata pre-filtering simplify index maintenance and reduce idle memory footprint, but separate collections offer stronger physical isolation for compliance-heavy enterprise tenants.
Production Verification Checklist
- Store API key secrets hashed with SHA-256 or bcrypt; never store plaintext keys.
- Enforce tenant rate limits at both request-count and token-expenditure levels.
- Always use metadata pre-filters on all vector search and RAG retrieval queries.
- Log tenant ID with all request traces for unified billing and usage attribution.