The user wants a design for a "multi-tenant analytics backend with row filters and quotas."
1. Deconstruct the Request:
- Multi-tenant: Single application instance serving multiple customers (tenants). Data isolation is crucial (logical or physical).
- Analytics Backend: Needs to handle queries (likely aggregations, time-series), high read volume, potentially high write volume (ingestion), and storage of large datasets.
- Row Filters: Users/Tenants should only see data they are authorized to see. This isn't just "Tenant A sees Tenant A's data," but potentially finer-grained control (e.g., "Team X within Tenant A sees Region Y data").
- Quotas: Limits on resources. This usually means:
- Ingestion Quotas: How much data can a tenant send per day/month?
- Query Quotas: How many queries can a tenant run? How much data is scanned?
- Storage Quotas: How much total data can a tenant keep?
2. High-Level Architecture Strategy:
- Database Choice: Relational (Postgres) vs. NoSQL (Mongo) vs. OLAP (ClickHouse, Snowflake, BigQuery). Since it's analytics, an OLAP columnar store is usually the best fit for performance.
- Tenancy Model:
- Shared Database, Shared Schema: Cheapest, hardest to isolate. Add
tenant_id column to everything.
- Shared Database, Separate Schema: Better isolation, harder to manage migrations.
- Separate Database: Best isolation, most expensive/complex infrastructure.
- Hybrid/Serverless: Use cloud-native features (RLS, workload management).
- Decision: For this design, I'll assume a "Shared Database" approach (most common for SaaS) but implemented on an OLAP engine for speed, or a standard RDBMS if scale isn't massive. I'll lean towards PostgreSQL (accessible, supports RLS) or ClickHouse (performance) concepts. Let's go with a generic modern stack (API Gateway -> Service -> OLAP Store).
3. Detailed Component Design:
-
Ingestion Layer:
- Needs to check quotas before writing.
- Async processing (Kafka/Queue) to decouple ingestion from writing.
- Validation.
-
Query Layer (The Core):
- Needs to inject Row Filters automatically.
- Needs to check Query Quotas (cost estimation).
-
Metadata/Config Store:
- Stores quota definitions, tenant hierarchies, role definitions.
4. Addressing Specific Requirements:
5. Structuring the Design Document:
- Phase 1: High-Level Architecture (The Diagram): Visualizing the flow.
- Phase 2: Database Schema & Tenancy Strategy: How data is stored.
- Phase 3: Row-Level Security (The Filters): The logic for access control.
- Phase 4: Quota Management: The mechanism for limits.
- Phase 5: API Design: How clients interact.
- Phase 6: Scalability & Optimization: Caching, Partitions.
6. Drafting the Content (Self-Correction during drafting):
-
Initial thought: Just use Postgres RLS.
-
Critique: RLS is great, but if using a specialized OLAP (like ClickHouse or Snowflake), RLS might not be as robust or standard. I should offer two patterns:
- The "Middleware SQL Rewriter" (Works with any SQL DB like ClickHouse/Trino).
- The "Native RLS" (Postgres approach).
Decision: I will describe the Middleware/Service Layer approach as it's database-agnostic and offers more control over complex filter logic (like joining user attributes).
-
Quota Logic: How to count rows efficiently?
- Don't count every row on every insert.
- Use a "Token Bucket" or "Leaky Bucket" algorithm in Redis for API rate limiting.
- For storage quotas, aggregate usage daily or use database metadata tables.
7. Refining the "Analytics" aspect:
- Analytics implies reading.
- Performance is key. Partitioning by Tenant ID is mandatory to prevent a query for Tenant A from scanning Tenant B's data.
8. Final Polish:
- Make sure to mention specific technologies (Redis, Kafka, Postgres/ClickHouse) to make it concrete, but keep the logic generalizable.
- Structure with clear headings and code snippets for the complex parts (SQL rewriting).
(Self-Correction on Row Filters):
The prompt mentions "Row Filters" specifically. This usually implies customers define the filters for their users.
- Scenario: SaaS provider (Me) -> Tenant Admin -> Tenant User.
- Tenant Admin creates a "Sales Rep" role and says "Sales Rep can only see rows where
region = 'west'".
- My backend needs to store this rule and apply it when the User queries.
9. Final Output Generation: (Proceeding to generate the response following this structure).
- Architecture Diagram (ASCII).
- Database Design (Partitioning).
- Security (ABAC + SQL Rewriting).
- Quotas (Redis + DB Metadata).
- Tech Stack suggestions.
This design outlines a scalable, secure, and performant architecture for a multi-tenant analytics backend. It focuses on three critical pillars: Data Isolation, Access Control (Row Filters), and Resource Governance (Quotas).
1. High-Level Architecture
We will use a Shared Database (Logical Isolation) approach. This provides the best balance of cost-efficiency and maintenance overhead for SaaS analytics.
- Ingestion: Kafka + Apache Flink (for real-time validation and tenant tagging).
- Storage: OLAP Database (ClickHouse or Snowflake) utilizing Partitioning and Row-Level Security.
- Compute: Stateless API Services (Go/Rust) or a SQL-Gateway.
- Control Plane: Manages tenant metadata, quota limits, and RBAC rules.
graph TD
Client[Client SDK] --> API[API Gateway]
API --> AuthService[Auth Service]
API --> QueryService[Query Service]
subgraph "Control Plane"
MetaDB[(Metadata DB)]
QuotaService[Quota Limiter]
end
QueryService --> MetaDB
QueryService --> QuotaService
QueryService --> OLAP[(OLAP Store)]
subgraph "Ingestion Pipeline"
IngestAPI[Ingestion API] --> Kafka
Kafka --> Flink[Stream Processor]
Flink --> OLAP
end
2. Database Schema & Tenancy Strategy
To ensure performance, we must physically organize data by tenant while keeping it logically unified.
Strategy: Partitioning by Tenant ID.
Every table includes a tenant_id as the primary partition key. This ensures that a query for Tenant A never scans the disk blocks belonging to Tenant B.
Example Schema (ClickHouse/PostgreSQL):
CREATE TABLE analytics_events (
event_id UUID,
tenant_id VARCHAR(64), -- The Partition Key
user_id VARCHAR(64),
event_type VARCHAR(50),
payload JSONB,
created_at TIMESTAMP
) PARTITION BY LIST (tenant_id);
3. Row-Level Security (The "Row Filters")
Row filters ensure that users within a tenant can only see data they are authorized to view (e.g., a "Regional Manager" only sees data from their region).
There are two main approaches to implement this. Option A (DB-Level) is preferred for security; Option B (App-Level) is preferred for database flexibility.
Option A: Native Row-Level Security (PostgreSQL/Snowflake)
We create database roles dynamically or use session variables.
- The Policy: The database enforces the filter.
-- PostgreSQL Example
CREATE POLICY tenant_isolation_policy ON analytics_events
USING (tenant_id = current_setting('app.current_tenant'));
CREATE POLICY region_access_policy ON analytics_events
USING (region_id IN (SELECT region_id FROM user_permissions WHERE user_id = current_setting('app.user_id')));
- The Execution: The Application Service sets the session variable (
SET app.current_tenant = 'tenant_123') immediately upon connecting. No data can leak, even if the SQL query is malformed.
Option B: Application-Side SQL Rewriting (Recommended for OLAP)
If using ClickHouse or a DB without robust RLS, the Query Service must parse the incoming SQL and inject WHERE clauses.
Implementation Logic (SQL Parser):
Use a library like JSqlParser (Java) or pg_query (Go) to traverse the Abstract Syntax Tree (AST).
- Find the
FROM clause.
- Inject the
tenant_id predicate (Hard Filter).
- Inject the User Attribute predicates (Soft Filter).
- Validate that the query does not access unauthorized tables.
4. Quota Management (The Governance)
Quotas prevent a "Noisy Neighbor" scenario where one tenant consumes all database resources.
A. Ingestion Quotas (Rate Limiting)
Limits how much data a tenant can push.
- Mechanism: Token Bucket Algorithm using Redis.
- Check:
INCR key quota:ingest:{tenant_id} with a TTL (daily/hourly).
- Action: If count > limit, reject HTTP 429 (Too Many Requests) before writing to Kafka.
B. Query Quotas (Compute/Cost)
Limits how expensive a query can be.
- Type 1: Concurrency Limit: Max 5 concurrent queries per tenant.
- Impl: Semaphore per tenant ID in the application memory.
- Type 2: Data Scanned Limit (Cost): "You can only scan 1GB per query."
- Impl: Most OLAP DBs (BigQuery, Snowflake, ClickHouse) return a "bytes scanned" statistic after execution. For strict enforcement, we use a Chain of Responsibility pattern:
- Dry Run: Send query to DB with
EXPLAIN or dry_run=true to get estimated byte cost.
- Check: If
est_bytes > quota, reject.
- Execute: If
est_bytes < quota, run query.
- Deduct: Deduct actual cost from the tenant's monthly budget in Redis/DB.
5. API Design
Endpoint: POST /api/v1/query
Request:
{
"query": "SELECT sum(cost) FROM clicks WHERE timestamp > NOW() - INTERVAL '1 day'",
"format": "json"
}
Middleware Pipeline:
- Auth Middleware: Validates JWT. Extracts
tenant_id and user_role. Populates UserContext.
- Quota Middleware (Pre-flight):
- Check Redis for concurrent queries.
- If concurrency exceeded -> HTTP 429.
- SQL Rewriter:
- Parse SQL.
- Inject
WHERE tenant_id = :ctx_tenant_id.
- Inject Row Filters based on
user_role.
- Cost Estimator:
- Send
EXPLAIN to DB.
- If estimated rows/bytes > Tenant Limit -> HTTP 403 (Quota Exceeded) or 422 (Query Too Complex).
- Executor:
- Send rewritten query to DB.
- Stream results back to client.
6. Tech Stack Recommendations
- Database:
- High Concurrency/Low Latency: ClickHouse (Fast reads, strict quota support via
settings max_bytes_read).
- Enterprise/Flexible: Snowflake (Multi-cluster shared data, native RLS).
- Open Source/Transactional: PostgreSQL (Robust RLS, but harder to scale for heavy analytics).
- Query Service: Go or Rust (High concurrency, efficient memory usage for streaming results).
- Metadata Store: PostgreSQL (Stores tenant configurations, quota limits).
- Rate Limiting: Redis.
7. Summary of Data Flow
- Ingest: Data comes in via API -> Kafka -> Flink (validates schema) -> DB.
tenant_id is injected at the Gateway or Flink stage.
- Query:
- User sends SQL.
- Backend rewrites SQL:
SELECT * FROM t -> SELECT * FROM t WHERE tenant_id='X' AND user_filter='Y'.
- Backend runs
EXPLAIN. Est. cost is 500MB. Tenant limit is 1GB. OK.
- Backend executes query.
- Backend logs usage to billing system.
This architecture ensures strict isolation without the overhead of running separate databases, while protecting the system from runaway queries or heavy tenants.