We are going to design a tenant isolation layer for a multi-tenant system. The requirements are:
- Row-Level Security (RLS) to ensure tenants can only access their own data.
- Quotas to limit resource usage per tenant.
- Fairness to prevent a noisy neighbor from affecting others.
- Hotspots to identify and handle tenants that are using resources in an unbalanced way (e.g., one table or partition is heavily used).
We assume we are using a relational database (like PostgreSQL) that supports RLS. We also assume we have a way to identify the tenant (e.g., a tenant_id column in every table).
Steps:
-
RLS:
- Enable RLS on all tables that contain tenant data.
- Create a policy for each table (or use a generic policy if the database supports it) that restricts access to rows where
tenant_id matches the current tenant's ID.
- We need a way to set the current tenant's ID for the session. This can be done by setting an application context variable (e.g.,
app.current_tenant_id).
-
Quotas:
- We need to track resource usage per tenant. Resources could be:
- Number of rows (per table or overall)
- Storage size (per table or overall)
- Number of API calls (if we are counting at the application level)
- Compute time (if we can measure)
- We can have a
quotas table that defines the limits for each tenant (or a default for all tenants). Example:
CREATE TABLE quotas (
tenant_id UUID PRIMARY KEY,
max_rows BIGINT,
max_storage_bytes BIGINT,
max_api_calls_per_hour INT,
...
);
- We also need to track current usage. We can have a
usage table that is updated periodically (or in real-time) with the current usage for each tenant and resource.
- We can enforce quotas at the application level by checking before allowing an operation. Alternatively, we can use database triggers or event triggers to track usage and block when a quota is exceeded.
-
Fairness:
- Fairness can be implemented by:
- Using resource queues (if the database supports it, like in PostgreSQL with pg_qos or similar) to limit the amount of resources (CPU, I/O) per tenant.
- At the application level, we can use rate limiting per tenant for API calls.
- We can also use connection pooling with per-tenant limits.
-
Hotspots:
- We need to monitor which tables or partitions are being accessed heavily by a particular tenant.
- We can track the number of queries per table per tenant, or the amount of I/O per table per tenant.
- We can have a
hotspots table that records:
tenant_id, table_name, query_count, last_updated
- We can update this table periodically (or in real-time) by collecting statistics from the database (e.g., using pg_stat_statements in PostgreSQL, but that is per query, not per tenant and table).
- Alternatively, we can create our own logging of queries and then aggregate by tenant and table.
Implementation Details:
RLS in PostgreSQL:
Step 1: Enable RLS on a table.
ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;
Step 2: Create a policy that uses the current tenant ID.
CREATE POLICY tenant_isolation_policy ON table_name
USING (tenant_id = current_setting('app.current_tenant_id')::UUID);
We need to set the `app.current_tenant_id` for each session. This can be done by the application after authenticating the tenant.
However, note that if we have tables that don't have a `tenant_id` (like shared reference tables) we might not want to apply RLS on them. So we need to be selective.
Quotas:
We can have a background job that periodically (e.g., every hour) updates the `usage` table for each tenant.
For row count per table, we can run:
SELECT tenant_id, COUNT(*) FROM table_name GROUP BY tenant_id;
For storage, we can use the database's system tables to get the size of each table and then multiply by the tenant's share (if the table is partitioned by tenant, then we can get the size per partition).
Alternatively, we can use triggers to increment counts on insert/update/delete, but that might be heavy.
We can also use event triggers to track DDL and DML, but that's complex.
A simpler approach: have a materialized view that aggregates the counts and sizes, and refresh it periodically.
Then, when a tenant tries to perform an operation, we check the current usage against the quota. If exceeded, we block.
Fairness:
In PostgreSQL, we can use the pg_qos extension (if available) to set resource limits per user or per database. But note that our tenants are not separate database users. They are all using the same application user.
Alternatively, we can create a separate database user for each tenant and then set resource limits per user. But that might be heavy for connection pooling.
Another approach: use application-level rate limiting. We can have a middleware that counts the number of requests per tenant and blocks if they exceed a threshold.
Hotspots:
We can log every query with the tenant ID and the table(s) accessed. Then, we can aggregate by tenant and table to see which tables are hot for which tenant.
We can use the `pg_stat_statements` extension and then try to parse the query to get the table name, but that's not straightforward.
Alternatively, we can use log_line_prefix to include the tenant ID in the log, and then process the logs.
Or, we can set up a trigger on each table that logs every access (read/write) to a separate table, but that would be very heavy.
A more practical approach: use a background job that samples the active queries from `pg_stat_activity` and records the tenant and the tables they are accessing. But note that `pg_stat_activity` does not show the tables, only the query text.
We can parse the query text to extract table names, but that's complex and error-prone.
Alternatively, we can use the `pg_stat_user_tables` to see which tables are being accessed, but that is per database, not per tenant.
So, we might need to rely on application-level logging: the application knows which tenant is making which request and which tables are involved. We can log that and then aggregate.
Given the complexity, we might decide that hotspots are for internal monitoring and we can use a combination of database statistics and application logs.
Putting it all together:
We'll design:
-
A way to set the tenant context in the database session.
-
RLS policies on all tenant tables.
-
A quotas table and a usage table (or materialized view).
-
Application-level checks for quotas (or database triggers if we want to be strict).
-
Application-level rate limiting for fairness.
-
Application-level logging for hotspots, and a background job to aggregate and report.
However, note that the requirement says "create a tenant isolation layer", so we might want to do as much as possible in the database to avoid trusting the application.
Let's try to do as much in the database as possible:
- RLS: done in database.
- Quotas: we can try to enforce in database by using triggers that check the current usage and then raise an exception if the quota is exceeded. But note that triggers can be bypassed (if someone has superuser) and they add overhead.
Alternatively, we can use security definer functions that check quotas and then perform the operation. But then we have to change all application queries to use these functions.
Given the complexity and performance impact, it's common to enforce quotas at the application level and use RLS for isolation.
So, we'll design:
Database:
- RLS policies on all tenant tables.
- A quotas table (for each tenant, the limits).
- A usage table (or materialized view) that is updated periodically (or by triggers) with the current usage.
Application:
- Set the tenant context in the database session.
- Before performing a write operation, check the relevant quota (by reading the usage table and comparing to quotas). If exceeded, throw an error.
- Implement rate limiting for API calls (using a token bucket or similar) per tenant.
Monitoring:
- Log every request with tenant ID and the tables involved.
- Aggregate these logs to find hotspots.
However, if we want to enforce quotas in the database, we can do:
Option 1: Triggers on every table that update a counter and then check against the quota. But that would be very heavy and also we have to handle concurrent updates.
Option 2: Use event triggers to capture DML and then update a central table. But again, performance.
Given the trade-offs, I think it's acceptable to do quota checks at the application level and rely on RLS for isolation.
But note: if the application is compromised or buggy, it might bypass the quota check. So we want at least a safety net in the database.
We can do:
- Create a function that checks the quota and then performs the operation. But then we have to rewrite all the application's SQL to call that function.
Alternatively, we can use a proxy that intercepts SQL and enforces quotas. But that's complex.
Let's stick with:
- RLS in database.
- Quotas: application-level check with a cached version of the usage (to avoid hitting the database on every request) and then periodically update the usage from the database.
For fairness, we do application-level rate limiting.
For hotspots, we do application-level logging and aggregation.
Steps for implementation:
-
Database setup:
a. For each table that has tenant data, add a tenant_id column (if not already present).
b. Enable RLS and create a policy for each table (or one policy that can be used on multiple tables if the column name is the same and we use a generic policy function).
In PostgreSQL, we can create a policy that uses a function to get the current tenant ID.
Example:
CREATE OR REPLACE FUNCTION current_tenant_id()
RETURNS UUID AS $$
BEGIN
RETURN current_setting('app.current_tenant_id', true)::UUID;
END;
$$ LANGUAGE plpgsql;
Then create a policy:
CREATE POLICY tenant_isolation_policy ON table_name
USING (tenant_id = current_tenant_id());
We can create this policy on every table.
c. Create the quotas table:
CREATE TABLE quotas (
tenant_id UUID PRIMARY KEY,
max_rows BIGINT NOT NULL,
max_storage_bytes BIGINT NOT NULL,
max_api_calls_per_hour INT NOT NULL,
...
);
d. Create a usage table (or materialized view) that aggregates the current usage.
We can have a materialized view that refreshes every hour:
CREATE MATERIALIZED VIEW tenant_usage AS
SELECT
tenant_id,
COUNT(*) as total_rows,
pg_database_size(current_database()) as total_db_size, -- but this is for the whole database, not per tenant.
...
FROM
(SELECT tenant_id FROM table1
UNION ALL
SELECT tenant_id FROM table2 ...) as all_tenant_data
GROUP BY tenant_id;
But note: the above does not give per-table breakdown and the storage is tricky.
Alternatively, we can have a function that calculates the usage per tenant by summing the sizes of the partitions (if we are using partitioned tables by tenant) or by using the statistics from the system tables.
Since it's complex, we might decide to track only row counts and leave storage for a separate background process that estimates.
For simplicity, let's track:
- total_rows: total number of rows across all tenant tables for a given tenant.
- table_rows: we can break down by table if needed.
We can create a table `tenant_table_usage`:
CREATE TABLE tenant_table_usage (
tenant_id UUID,
table_name TEXT,
row_count BIGINT,
last_updated TIMESTAMP
);
And update it periodically.
e. We can also have a table hotspots:
CREATE TABLE hotspots (
tenant_id UUID,
table_name TEXT,
query_count BIGINT,
last_updated TIMESTAMP
);
-
Application:
a. After authenticating the tenant, set the session variable:
SET app.current_tenant_id = 'tenant-uuid';
b. Before writing, check the quota:
Read from the `usage` table (or materialized view) for the tenant and compare with the `quotas` table.
We can cache the usage in the application to avoid hitting the database on every request.
We must ensure that the cache is invalidated when the usage updates (or use a short TTL).
This is a high-level design. The actual implementation will depend on the specific database and application framework.
Note: The RLS policy must be created on every table that contains tenant data. We might want to automate this with a script.
Also, note that if we have foreign keys between tables of different tenants, we must ensure that the referenced row is in the same tenant. We can do that by including tenant_id in the foreign key, or by having a trigger that checks.
With RLS, the foreign key check might not work as expected because the referenced row might be from a different tenant and the policy would filter it out. So we must design the foreign keys to include the tenant_id, or disable the foreign key and enforce at the application level.
Given the complexity, it's better to include the tenant_id in every foreign key that crosses tenant boundaries (which should not happen if we are properly isolating). Actually, we should not have foreign keys between tables of different tenants. So we can design the schema so that all tables are isolated per tenant (by having tenant_id in every table and then having foreign keys that also include tenant_id).
Example:
Table: orders (tenant_id, id, ...)
Table: order_items (tenant_id, order_id, ...)
Then the foreign key from order_items to orders must be on (tenant_id, order_id) to ensure that the order item points to an order of the same tenant.
This design requires that every table that is part of a relational chain has the tenant_id and that the foreign keys are composite.
Alternatively, we can have a separate schema per tenant? But that is not scalable for many tenants.
So, we stick with one schema and include tenant_id in every table and in every foreign key.
This design is known as "shared database, shared schema" with tenant_id in every table.
Let's adjust the RLS policy to also check the tenant_id in the foreign key relationships? Actually, the RLS policy on the parent table will already filter by tenant_id, so the child table's foreign key must also have the same tenant_id. So we must design the foreign keys to include tenant_id.
Steps for foreign keys:
When creating a foreign key, we must include the tenant_id column.
Example:
CREATE TABLE orders (
tenant_id UUID NOT NULL,
id UUID NOT NULL,
...,
PRIMARY KEY (tenant_id, id)
);
CREATE TABLE order_items (
tenant_id UUID NOT NULL,
order_id UUID NOT NULL,
...,
PRIMARY KEY (tenant_id, order_id, ...),
FOREIGN KEY (tenant_id, order_id) REFERENCES orders(tenant_id, id)
);
Then, the RLS policy on both tables will ensure that the tenant_id matches.
This design ensures that even if someone tries to insert an order_item with a different tenant_id, it will fail because the referenced order must have the same tenant_id (and the RLS policy will filter the order to the current tenant).
However, note that the foreign key check in PostgreSQL does not use RLS. It checks the actual row in the referenced table. But if we have RLS enabled on the referenced table, the check will be done with the current tenant's RLS policy. So it will only see rows of the current tenant. Therefore, if we try to insert an order_item with a tenant_id that is not the current tenant, then the referenced order (with that tenant_id) will not be visible because of RLS, and the foreign key will fail.
So we are safe.
Summary:
We have:
-
RLS on every tenant table, using a policy that checks tenant_id = current_tenant_id().
-
A quotas table and a usage table (or materialized view) that is updated periodically.
-
Application-level quota checks (using the usage table) and rate limiting.
-
Application-level logging for hotspots.
This should meet the requirements.
However, note that the usage table must be kept up to date. We can use triggers to update counts, but that might be heavy. Alternatively, we can refresh a materialized view every hour (or more frequently) and use that for quota checks. But then the quota check might be stale.
We can also use a combination: real-time checks for critical quotas (like maximum rows per table) using triggers, and periodic checks for others.
Given the complexity, we might decide to only check quotas on write operations and use a cached version of the usage (with a short TTL) to avoid hitting the database.
Let's design the quota check in the application:
Step 1: Get the current usage for the tenant (from cache or database).
Step 2: Get the quota for the tenant (from cache or database).
Step 3: If the current usage + the estimated impact of the operation (e.g., one row for insert, or the size of the data) exceeds the quota, then reject.
The estimated impact might be hard to calculate for updates (if the row size changes). So we might be conservative and assume the worst case (max row size) or we can check after the operation and then rollback if exceeded? But that would be after the fact.
Alternatively, we can do:
- For inserts: check the row count and storage. If after the insert the row count would exceed the quota, then reject.
- For updates: if the update changes the size of the row, then we have to consider the storage quota. We can check the current row size and the new row size and see the difference.
- For deletes: we don't need to check because it reduces usage.
But note: concurrent operations might cause the quota to be exceeded even if we check. So we need to do the check and the operation in a transaction and use row locking on the usage table? That would be heavy.
Given these challenges, we might decide that quotas are best effort and we refresh the usage periodically and then use that for checking. We accept that in a high concurrency situation, we might go slightly over the quota, and then we have a background job that cleans up (or we just allow it and then the next check will block further operations).
Alternatively, we can use a database sequence for row counts and then check the sequence value? But that would be for the whole table, not per tenant.
Given the complexity, I think we should:
- For row count: we can have a counter table that is updated by triggers on insert/delete. Then we can check that counter in the same transaction as the insert/delete. But that would be a lot of triggers.
- For storage: we can approximate by the row count and average row size, or we can use the database's statistics.
Given the time, let's stick with the periodic refresh and application-level check, and note that it's not perfectly accurate.
We can improve by:
- Having a trigger on each table that updates a `tenant_counters` table (with tenant_id, table_name, row_count) on every insert/delete. Then we can check that table in the same transaction.
But then we have to update the `tenant_counters` table in the same transaction as the user's transaction. That would add overhead.
We might decide that the quotas are soft and we check periodically and then notify the tenant if they are over, and then take action (like blocking further writes) only after they are over for a while.
So, let's go with:
- RLS: hard isolation.
- Quotas: soft, checked by the application with a cached version of the usage (refreshed every 5 minutes, for example).
- Fairness: rate limiting at the application level.
- Hotspots: logged by the application and aggregated.
This is a pragmatic approach.
Code for RLS:
We assume we have a function `current_tenant_id()` that returns the current tenant ID from the session variable.
Then for each table:
ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON table_name
USING (tenant_id = current_tenant_id());
We must also consider that the `current_tenant_id` function returns NULL if the variable is not set. We want to block access if the tenant is not set. We can change the policy to:
USING (tenant_id = current_tenant_id() AND current_tenant_id() IS NOT NULL)
But then if the variable is not set, no rows are visible. That's safe.
We must also consider that the current_tenant_id function might be called in a context where the variable is not set (like during table creation). We can set a default value for the variable? Actually, the function will return NULL and then the policy will filter out all rows. That's acceptable.
We must set the variable for every session that the application uses.
Steps for the application:
After authenticating the tenant, for every database connection:
SET app.current_tenant_id = 'the-tenant-uuid';
We can do this in the connection pool when the connection is borrowed by the application.
That's it for RLS.
For quotas, we'll have:
Table quotas:
tenant_id (PK)
max_rows (bigint)
max_storage_bytes (bigint)
max_api_calls_per_hour (int)
Table usage (maybe a materialized view):
tenant_id
total_rows (bigint)
total_storage_bytes (bigint)
api_calls_last_hour (int)
We update the `usage` table periodically (every 5 minutes) by:
- Counting rows per tenant for each table and summing.
- Estimating storage: we can use the sum of the pg_total_relation_size for each table, but that is for the whole table. We need per tenant. If we are using partitioned tables by tenant, then we can get the size of each partition. Otherwise, we have to estimate by the row count and average row size.
Alternatively, we can use the `pg_stat_user_tables` to get the total size and then divide by the total rows and multiply by the tenant's row count? That's an estimate.
We can also use the `pg_column_size` for each row? That's heavy.
Given the complexity, we might skip storage quota and only do row count and API calls.
So, let's change the `usage` table to:
tenant_id
total_rows
api_calls_last_hour
And we can have a background job that:
- Updates `total_rows` by counting rows per tenant (for all tenant tables) and summing.
- Resets `api_calls_last_hour` every hour and then increments as the application makes API calls (the application can also update this counter in real-time with a database insert? But that would be heavy).
Alternatively, we can track API calls in a separate table with a timestamp and then count the ones in the last hour. But that table would grow fast.
We can use a Redis or similar for rate limiting and then update the `usage` table every hour with the count from Redis? But then we are not using the database.
Given the requirement of using the database, we can:
- Have a table `api_calls`:
tenant_id, timestamp
And then count the rows in the last hour for each tenant.
But that table will be huge. We can partition it by month and then drop old partitions.
Alternatively, we can use a materialized view that refreshes every hour and counts the api_calls in the last hour.
But then we are not real-time.
We can do:
- The application increments a counter in Redis for the tenant for the current hour.
- And also writes an event to a table (for auditing) but not for quota.
Then, for quota, we can use the Redis counter for real-time and update the `usage` table from Redis every hour.
But the requirement says "create a tenant isolation layer" and we are using Redis, which is outside the database.
So, let's stick with the database:
We'll have a table `api_calls`:
id (bigserial)
tenant_id (uuid)
called_at (timestamp)
We can partition this table by `called_at` (by day or month).
Then, the usage for `api_calls_last_hour` is:
SELECT COUNT(*) FROM api_calls
WHERE tenant_id = current_tenant_id()
AND called_at >= now() - interval '1 hour'
We can cache this count in the application for a short time (like 1 minute) to avoid hitting the database on every API call.
But then the application must insert a row into `api_calls` for every API call? That would be heavy.
Alternatively, we can have a trigger on the API call (at the application level) that inserts into `api_calls`? But that would be the same.
We can use a separate service that aggregates the API calls from the application logs and then inserts into `api_calls`? That's batch.
Given the performance impact, we might decide to not track API calls at the database level and rely on application-level rate limiting (with in-memory counters) and then update the `usage` table periodically (every hour) by reading the application's rate limiter state? That's not reliable.
So, we are in a dilemma.
Let's re-evaluate:
The requirement says "quotas", and one of them is API calls. We want to limit the number of API calls per hour.
We can do:
- Application-level rate limiting using a token bucket in Redis. That's real-time and efficient.
- Then, for the `usage` table, we can update the `api_calls_last_hour` from the Redis counter (by having a background job that reads the Redis keys and updates the database). This way, the quota check in the application (which uses the `usage` table) is eventually consistent.
But then the quota check might be off by up to an hour.
Alternatively, we can have the application update the `usage` table in real-time for API calls? That would be:
BEGIN;
UPDATE usage SET api_calls_last_hour = api_calls_last_hour + 1 WHERE tenant_id = ...;
COMMIT;
And then we check the quota by:
SELECT api_calls_last_hour FROM usage WHERE tenant_id = ... FOR UPDATE; -- to lock the row
Then check and then update.
But that would be a transaction per API call and would be a bottleneck.
We can use a stored procedure that does the check and increment in one transaction, and then the application calls that procedure.
CREATE OR REPLACE FUNCTION increment_api_call(p_tenant_id UUID) RETURNS BOOLEAN AS $$
DECLARE
current_calls INT;
max_calls INT;
BEGIN
SELECT api_calls_last_hour, max_api_calls_per_hour
INTO current_calls, max_calls
FROM usage u JOIN quotas q ON u.tenant_id = q.tenant_id
WHERE u.tenant_id = p_tenant_id
FOR UPDATE; -- lock the row to prevent concurrent overuse
IF current_calls >= max_calls THEN
RETURN FALSE;
END IF;
UPDATE usage SET api_calls_last_hour = api_calls_last_hour + 1 WHERE tenant_id = p_tenant_id;
RETURN TRUE;
END;
$$ LANGUAGE plpgsql;
Then the application does:
SELECT increment_api_call('tenant-uuid');
If it returns true, then continue, else reject.
But note: the `usage` table must have a row for every tenant. We can use a trigger to create a row in `usage` when a new tenant is created.
Also, we must reset the `api_calls_last_hour` every hour. We can have a cron job that resets it to 0 for all tenants, or we can have a rolling window by storing the timestamps of each call (as we thought earlier) and then counting the last hour. But then the function above would have to count the number of calls in the last hour, which is expensive.
Given the complexity, I think we should:
- For API calls: use application-level rate limiting (with Redis) and then update the `usage` table from Redis every hour (or in real-time if we want the `usage` table to be accurate for other purposes). But then the quota check in the application (which uses the `usage` table) is not real-time.
- Or, we can have the application update the `usage` table in real-time and also use Redis for rate limiting? That's redundant.
Let's decide:
We want to enforce the quota at the application level (to avoid hitting the database on every call) and we want the database to have an accurate record for monitoring.
So:
- The application uses Redis to do rate limiting (token bucket). If the token bucket is empty, reject.
- The application also asynchronously updates the `usage` table (maybe every minute) with the current count from Redis? But then the `usage` table is not real-time.
Alternatively, we can have the application update the `usage` table on every API call? That would be too heavy.
We can do:
- The application updates the `usage` table in batches: every time it makes an API call, it increments a local counter. Then, every 60 seconds, it flushes the counter to the database.
Then, the quota check for API calls is done by the application using the local counter and the Redis token bucket. The `usage` table is only for monitoring.
But then the quota is enforced by the application's local counter and Redis, and the database `usage` table is just for show.
Given the requirement, we want the database to be the source of truth for quotas? Not necessarily.
The requirement says "quotas", and we are implementing them. It doesn't specify where.
So, I think it's acceptable to enforce quotas at the application level.
Therefore, we can skip the `usage` table for API calls and only use it for row count and storage.
For row count and storage, we can do:
- The application, before an insert, checks the current row count (from a cached value) and the quota. Then, if the insert is allowed, it increments the cached row count and also updates the database's `usage` table asynchronously? But then the cached value might be off if there are concurrent writes.
We can use a database sequence for the row count per tenant? But then we have to have a sequence per table and per tenant? That's not feasible.
Given the challenges, we might decide:
- For row count: we can have a trigger that updates a `tenant_counters` table (with tenant_id, table_name, row_count) on every insert/delete. Then, when the application wants to check the quota, it reads from `tenant_counters` (which is updated in the same transaction as the user's transaction) and then checks. But that would require reading the `tenant_counters` table in the same transaction? And then we have to lock the row in `tenant_counters` to prevent overuse.
Example:
BEGIN;
SELECT row_count FROM tenant_counters WHERE tenant_id = ... AND table_name = ... FOR UPDATE;
-- check if row_count + 1 > max_rows
-- then do the insert
-- and then update tenant_counters set row_count = row_count + 1 where ...;
COMMIT;
But then we are doing two writes (the user's insert and the update of the counter) and a read in the same transaction. And we are locking the counter row.
This might be acceptable if the number of tenants is not huge and the contention is low.
We can have one counter row per tenant per table? Or one row per tenant for all tables? We can have:
CREATE TABLE tenant_counters (
tenant_id UUID PRIMARY KEY,
total_rows BIGINT
);
Then, for every insert in any tenant table, we update this table. But then we have to update this table from every table's trigger? That's complex.
Alternatively, we can have a trigger that updates the `tenant_counters` table for the specific table? But then we have multiple triggers and we are updating the same row in `tenant_counters` for every insert in any table? That would be a hotspot.
So, we can have:
CREATE TABLE tenant_counters (
tenant_id UUID,
table_name TEXT,
row_count BIGINT,
PRIMARY KEY (tenant_id, table_name)
);
Then, for each table, we have a trigger that updates the corresponding row in `tenant_counters`.
Then, when we want to check the quota for a specific table, we read the `tenant_counters` for that table and tenant.
But the quota might be for the total rows across all tables. Then we have to sum the row counts for all tables for that tenant.
We can have a materialized view that sums the row counts per tenant and then use that for the total row quota.
But then we are back to the problem of keeping the materialized view up to date.
Given the time, I think we should:
- For row count quota: we check the `tenant_counters` table (which is updated by triggers in the same transaction as the user's transaction) and then if the total rows (sum of row_count for all tables) would exceed the quota, we reject.
But then we have to lock all the rows in `tenant_counters` for that tenant? That's not feasible.
Alternatively, we can use an advisory lock per tenant when checking the quota? That would serialize all writes for a tenant, which might be acceptable if the tenant is not huge.
Steps:
- In the application, when we want to do an insert:
1. Acquire an advisory lock for the tenant (so that only one transaction per tenant can check the quota at a time).
2. Read the current total rows for the tenant (from `tenant_counters` or by counting?).
3. Compare with the quota.
4. If okay, then do the insert and update the `tenant_counters` (or let the trigger update it).
5. Release the lock.
But then we are serializing all writes for a tenant, which might be a bottleneck.
We can do without the lock and accept that we might go over the quota by a few rows due to concurrency? Then we have a background job that cleans up (deletes rows) if the tenant is over the quota? That's not ideal.
Given the complexity, I think we should:
- Not enforce hard quotas for row count and storage at the database level. Instead, we monitor and alert, and then take action (like blocking further writes) when the tenant is over the quota.
- We can have a background job that checks the `tenant_counters` (which is updated by triggers) and if a tenant is over the quota, then we set a flag in the database (like `tenant_is_over_quota`) and then the application checks that flag before allowing writes.
But then there is a delay.
Given the time, I think we should keep it simple:
- RLS: implemented.
- Quotas: we monitor and alert, but do not block. We can have a soft limit and then discuss with the tenant.
- Fairness: application-level rate limiting.
- Hotspots: application-level logging.
This is a common approach in many multi-tenant systems.
So, the final design:
Database:
- RLS on all tenant tables with a policy that uses `current_tenant_id()`.
- `quotas` table: defines the limits.
- `tenant_counters` table (or materialized view) that tracks the current row counts per tenant and per table. Updated by triggers.
- `hotspots` table: updated by the application's logging aggregation.
Application:
- Set the tenant context.
- For each API call, check the rate limit (using Redis or in-memory).
- For write operations, check the `tenant_counters` (cached) and the `quotas` to see if we are over. If over, then we can warn or block (depending on policy).
- Log every request with tenant and tables.
- Background job that aggregates the logs and updates `hotspots`.
We can also have a background job that refreshes the `tenant_counters` from the actual table counts (to correct for any trigger failures) and then updates the `usage` table.
This is a compromise, but it's practical.
Let's write the SQL for the RLS and the tenant_counters table with triggers.
Example for one table:
CREATE TABLE tenant_counters (
tenant_id UUID,
table_name TEXT,
row_count BIGINT DEFAULT 0,
PRIMARY KEY (tenant_id, table_name)
);
We need to insert a row in `tenant_counters` for each table and tenant when the first row is inserted.
We can have a trigger function:
CREATE OR REPLACE FUNCTION update_tenant_counters()
RETURNS TRIGGER AS $$
BEGIN
IF (TG_OP = 'DELETE') THEN
UPDATE tenant_counters
SET row_count = row_count - 1
WHERE tenant_id = OLD.tenant_id AND table_name = TG_TABLE_NAME;
RETURN OLD;
ELSIF (TG_OP = 'INSERT') THEN
UPDATE tenant_counters
SET row_count = row_count + 1
WHERE tenant_id = NEW.tenant_id AND table_name = TG_TABLE_NAME;
IF NOT FOUND THEN
INSERT INTO tenant_counters (tenant_id, table_name, row_count)
VALUES (NEW.tenant_id, TG_TABLE_NAME, 1);
END IF;
RETURN NEW;
ELSIF (TG_OP = 'UPDATE') THEN
-- If the tenant_id changed, then we have to adjust two counters.
IF OLD.tenant_id <> NEW.tenant_id THEN
UPDATE tenant_counters
SET row_count = row_count - 1
WHERE tenant_id = OLD.tenant_id AND table_name = TG_TABLE_NAME;
UPDATE tenant_counters
SET row_count = row_count + 1
WHERE tenant_id = NEW.tenant_id AND table_name = TG_TABLE_NAME;
IF NOT FOUND THEN
INSERT INTO tenant_counters (tenant_id, table_name, row_count)
VALUES (NEW.tenant_id, TG_TABLE_NAME, 1);
END IF;
END IF;
RETURN NEW;
END IF;
END;
$$ LANGUAGE plpgsql;
Then, for each table:
CREATE TRIGGER tenant_counters_trigger
AFTER INSERT OR UPDATE OR DELETE ON table_name
FOR EACH ROW EXECUTE FUNCTION update_tenant_counters();
But note: this trigger will fire for every row change and update the `tenant_counters` table. This might be a performance bottleneck.
We can batch the updates? Not easily.
Alternatively, we can use a materialized view that we refresh periodically and skip the triggers.
Given the overhead, we might choose the materialized view approach and accept that the counters are stale by up to the refresh interval.
Let's do:
CREATE MATERIALIZED VIEW tenant_counters_mv AS
SELECT
tenant_id,
'table1' as table_name,
COUNT(*) as row_count
FROM table1
GROUP BY tenant_id
UNION ALL
SELECT
tenant_id,
'table2',
COUNT(*)
FROM table2
GROUP BY tenant_id
...;
Then, we refresh this materialized view every 5 minutes.
And then we have a `tenant_counters` table that is just a copy of the materialized view? Or we can use the materialized view directly for quota checks.
But then we cannot do real-time checks.
We can do:
- Use the materialized view for monitoring and for soft quota checks (which are not real-time).
- For hard quota, we need real-time. But we decided to do soft quotas.
So, we can use the materialized view for monitoring and for the application's quota check (with the understanding that it's stale). And then we also have triggers for real-time? That's too heavy.
Given the trade-offs, I think we should:
- For row count: use the materialized view and refresh every 5 minutes. The application uses this for quota checks (and accepts that it's stale). We can also have a background job that checks the materialized view and if a tenant is over the quota, then we set a flag in the `tenants` table (or a separate table) that says "over_quota". Then the application checks that flag before allowing writes.
But then the flag is only updated every 5 minutes.
Alternatively, we can have the application check the materialized view and then if the row count is close to the quota (say 90%), then we start rejecting inserts? But then we are still using stale data.
Given the complexity, I think we should abandon the idea of real-time row count quota and just monitor and alert.
So, final:
- RLS: implemented.
- Quotas: we have a `quotas` table and a materialized view `tenant_counters_mv` that is refreshed periodically. We use this for monitoring and for soft quota checks (with stale data). We do not block writes based on quotas, but we can warn the user and the tenant admin.
- Fairness: application-level rate limiting.
- Hotspots: application-level logging and aggregation.
This is a reasonable design.
Code:
We assume PostgreSQL.
Step 1: Create the function for RLS.
CREATE OR REPLACE FUNCTION current_tenant_id()
RETURNS UUID AS $$
BEGIN
RETURN current_setting('app.current_tenant_id', true)::UUID;
END;
$$ LANGUAGE plpgsql;
Step 2: For each tenant table, enable RLS and create the policy.
ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON table_name
USING (tenant_id = current_tenant_id());
Step 3: Create the quotas table.
CREATE TABLE quotas (
tenant_id UUID PRIMARY KEY,
max_rows BIGINT NOT NULL,
max_storage_bytes BIGINT NOT NULL,
max_api_calls_per_hour INT NOT NULL
);
Step 4: Create the materialized view for tenant counters.
We assume we have a fixed set of tables. We can generate the SQL for the materialized view.
Example for two tables:
CREATE MATERIALIZED VIEW tenant_counters_mv AS
SELECT tenant_id, 'table1' as table_name, COUNT(*) as row_count FROM table1 GROUP BY tenant_id
UNION ALL
SELECT tenant_id, 'table2' as table_name, COUNT(*) as row_count FROM table2 GROUP BY tenant_id;
Step 5: Create a job to refresh the materialized view every 5 minutes.
We can use pg_cron or a cron job that runs:
REFRESH MATERIALIZED VIEW tenant_counters_mv;
Step 6: Application:
- Set the tenant context.
- For rate limiting: use Redis.
- For quota check: read the materialized view and the quotas table and compare. If the tenant is over the quota (for any resource), then log a warning and possibly reject the operation (if we are enforcing).
- Log each request with tenant and tables.
Step 7: Background job that aggregates the logs and updates the `hotspots` table.
We can have a table `hotspots`:
CREATE TABLE hotspots (
tenant_id UUID,
table_name TEXT,
query_count BIGINT,
last_updated TIMESTAMP
);
The job runs every 5 minutes and:
INSERT INTO hotspots
SELECT tenant_id, table_name, COUNT(*) as query_count, NOW() as last_updated
FROM request_logs -- where request_logs has tenant_id and table_name (array of table names? or one row per table per request?)
WHERE logged_at > NOW() - interval '5 minutes'
GROUP BY tenant_id, table_name
ON CONFLICT (tenant_id, table_name) DO UPDATE
SET query_count = hotspots.query_count + EXCLUDED.query_count,
last_updated = NOW();
But note: the request_logs table might be huge. We can partition it by day and then drop old partitions.
This is a basic design.
We have not covered storage quota because it's hard to get per-tenant storage without partitioning by tenant. If we are using partitioned tables by tenant, then we can get the size of each partition. Otherwise, we have to estimate.
If we are not partitioned by tenant, we might skip the storage quota and only do row count.
Alternatively, we can use the materialized view to estimate storage by multiplying the row count by an average row size (which we can get from the database statistics). But that's an estimate.
Given the complexity, we might skip storage quota and only do row count and API calls.
Let's adjust:
quotas table:
tenant_id PK,
max_rows BIGINT,
max_api_calls_per_hour INT
And we remove max_storage_bytes.
This is a simplified version.
We can extend later if needed.
So, the final answer:
We'll create:
- RLS with a function that returns the current tenant_id from the session variable.
- A `quotas` table with max_rows and max_api_calls_per_hour.
- A materialized view `tenant_counters_mv` that has the row counts per tenant and per table.
- A `hotspots` table that is updated by a background job from the application logs.
- Application sets the tenant context, does rate limiting (for fairness) and checks the materialized view for row count quota (with stale data) and the `quotas` table for API call quota (which is enforced by the application's rate limiter).
This meets the requirements with a practical approach.
Note: The RLS policy must be created on every tenant table. We can write a script to do that.
Also, note that the materialized view does not include the total rows across all tables. We can have:
CREATE MATERIALIZED VIEW tenant_total_rows_mv AS
SELECT tenant_id, SUM(row_count) as total_rows
FROM tenant_counters_mv
GROUP BY tenant_id;
Then we can use that for the total row quota.
But we also want per-table breakdown for hotspots? The tenant_counters_mv already has per-table.
We can use tenant_total_rows_mv for the total row quota.
So, we have:
- `tenant_counters_mv` (tenant_id, table_name, row_count)
- `tenant_total_rows_mv` (tenant_id, total_rows)
Then, the application can check the tenant_total_rows_mv for the total row quota.
We can refresh both materialized views at the same time.
Alternatively, we can have one materialized view that has both per-table and total? But that would be redundant.
We'll keep them separate.
Steps for the application to check row quota:
SELECT total_rows FROM tenant_total_rows_mv WHERE tenant_id = current_tenant_id();
Then compare with the max_rows from the quotas table.
This is the design.
Let me know if you have any questions.
I'll design a comprehensive tenant isolation layer that addresses all your requirements: RLS, quotas, fairness, and hotspot detection. This is a layered architecture approach.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Application Layer │
├──────────────┬──────────────┬──────────────┬──────────────┤
│ API Gateway│ Middleware │ App Services│ Admin UI │
└──────────────┴──────────────┴──────────────┴──────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ Tenant Isolation Layer │
├──────────────┬──────────────┬──────────────┬──────────────┤
│ RLS │ Quotas │ Fairness │ Hotspots │
│ (Database) │ (Middleware)│ (Queue/Thrott)│ (Monitoring)│
└──────────────┴──────────────┴──────────────┴──────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ Shared Infrastructure │
├──────────────┬──────────────┬──────────────┬──────────────┤
│ PostgreSQL │ Redis/ │ Message │ Monitoring │
│ (RLS) │ Memcached │ Queue │ & Logging │
└──────────────┴──────────────┴──────────────┴──────────────┘
1. Row-Level Security (RLS)
Database Schema Design
-- Base table with tenant_id
CREATE TABLE tenants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
status VARCHAR(50) DEFAULT 'active',
created_at TIMESTAMP DEFAULT NOW()
);
-- All tenant data tables must include tenant_id
CREATE TABLE documents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
title VARCHAR(500),
content TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
-- Index for performance
CREATE INDEX idx_documents_tenant_id ON documents(tenant_id);
RLS Implementation (PostgreSQL example)
-- Enable RLS on all tenant tables
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
-- Policy that automatically filters by current tenant
CREATE POLICY tenant_isolation_policy ON documents
USING (tenant_id = current_setting('app.current_tenant_id')::UUID);
-- Function to set tenant context
CREATE OR REPLACE FUNCTION set_tenant_context(tenant_uuid UUID)
RETURNS void AS $$
BEGIN
PERFORM set_config('app.current_tenant_id', tenant_uuid::text, false);
END;
$$ LANGUAGE plpgsql;
-- Policy for admin override (if needed)
CREATE POLICY admin_override_policy ON documents
USING (current_setting('app.is_admin', true) = 'true');
Connection Pooling Configuration
# Example middleware to set tenant context
class TenantMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
tenant_id = self.extract_tenant_id(environ)
if tenant_id:
# Set tenant context for this request/connection
environ['tenant_id'] = tenant_id
return self.app(environ, start_response)
2. Quota System
Quota Definitions Table
CREATE TABLE tenant_quotas (
tenant_id UUID PRIMARY KEY REFERENCES tenants(id),
max_storage_bytes BIGINT DEFAULT 1073741824, -- 1GB
max_api_requests_per_hour INT DEFAULT 10000,
max_concurrent_connections INT DEFAULT 50,
max_document_count INT DEFAULT 10000,
max_bandwidth_per_day_bytes BIGINT DEFAULT 1073741824, -- 1GB/day
custom_limits JSONB DEFAULT '{}',
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Default quotas for new tenants
INSERT INTO tenant_quotas (tenant_id)
SELECT id FROM tenants WHERE NOT EXISTS (
SELECT 1 FROM tenant_quotas WHERE tenant_quotas.tenant_id = tenants.id
);
Real-time Quota Tracking Table
CREATE TABLE quota_usage (
id BIGSERIAL PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
resource_type VARCHAR(50) NOT NULL, -- 'storage', 'api_requests', etc.
current_value BIGINT DEFAULT 0,
period_start TIMESTAMP NOT NULL,
period_end TIMESTAMP NOT NULL,
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE(tenant_id, resource_type, period_start)
);
-- Partition by month for performance
CREATE TABLE quota_usage_2024_01 PARTITION OF quota_usage
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
Middleware Enforcement
class QuotaMiddleware:
def __init__(self):
self.redis = Redis() # For real-time counters
async def check_quota(self, tenant_id, resource_type, increment=1):
"""
Check and increment quota usage atomically
"""
# Get current period key
period_key = self._get_period_key(resource_type)
# Redis Lua script for atomic check-and-increment
lua_script = """
local current = redis.call('HGET', KEYS[1], ARGV[1])
local limit = tonumber(ARGV[2])
local increment = tonumber(ARGV[3])
if not current then
current = 0
end
if tonumber(current) + increment > limit then
return 0 -- Quota exceeded
end
redis.call('HINCRBY', KEYS[1], ARGV[1], increment)
return 1 -- Success
"""
# Get quota limit from database
quota = await self._get_quota_limit(tenant_id, resource_type)
# Check via Redis
result = redis.eval(lua_script, 1,
f"quota:{tenant_id}:{period_key}",
resource_type,
quota,
increment)
return result == 1
async def _get_quota_limit(self, tenant_id, resource_type):
# Cache this in Redis with TTL
cache_key = f"quota_limit:{tenant_id}"
limit = redis.get(cache_key)
if not limit:
# Fetch from database
# ... implementation
redis.setex(cache_key, 300, limit) # Cache 5 minutes
return limit
3. Fairness Engine
Token Bucket Algorithm Implementation
class FairnessManager:
def __init__(self):
self.redis = Redis()
async def acquire_token(self, tenant_id, resource_pool, tokens=1):
"""
Fair token bucket implementation per tenant
"""
key = f"tokens:{resource_pool}:{tenant_id}"
# Lua script for atomic token bucket refill and consumption
lua_script = """
local now = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local refill_rate = tonumber(ARGV[3]) -- tokens per second
local tokens_needed = tonumber(ARGV[4])
-- Get current state
local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens')) or capacity
local last_refill = tonumber(redis.call('HGET', KEYS[1], 'last_refill')) or now
-- Calculate tokens to add based on elapsed time
local elapsed = now - last_refill
local tokens_to_add = math.min(
capacity - tokens,
elapsed * refill_rate
)
-- Update state
tokens = math.min(capacity, tokens + tokens_to_add)
last_refill = now
if tokens >= tokens_needed then
tokens = tokens - tokens_needed
redis.call('HMSET', KEYS[1],
'tokens', tokens,
'last_refill', last_refill)
return 1 -- Success
else
redis.call('HMSET', KEYS[1],
'tokens', tokens,
'last_refill', last_refill)
return 0 -- Would block
end
"""
now = time.time()
# Different pools: 'cpu', 'io', 'network', 'database'
pool_config = self._get_pool_config(resource_pool)
return bool(redis.eval(lua_script, 1, key,
now,
pool_config['capacity'],
pool_config['refill_rate'],
tokens))
def _get_pool_config(self, pool_name):
# Base fair share ratios (adjust based on plan tier)
configs = {
'cpu': {'capacity': 1000, 'refill_rate': 10}, # tokens/sec
'io': {'capacity': 500, 'refill_rate': 5},
'database': {'capacity': 2000, 'refill_rate': 20},
'network': {'capacity': 1500, 'refill_rate': 15}
}
return configs.get(pool_name, {'capacity': 100, 'refill_rate': 1})
Queue-Based Throttling
from dataclasses import dataclass
from typing import Optional
@dataclass
class TenantPriority:
tenant_id: str
priority: int # 1-10, higher = more important
max_concurrent: int
weight: float # For weighted fair queuing
class FairPriorityQueue:
def __init__(self):
self.queues = {} # resource_type -> dict of tenant queues
self.redis = Redis()
async def schedule_request(self, tenant_id: str, resource_type: str,
priority: int, max_wait_ms: int = 1000):
"""
WFQ (Weighted Fair Queueing) implementation
"""
queue_key = f"queue:{resource_type}"
# Add tenant to weighted queue
tenant_priority = await self._get_tenant_priority(tenant_id)
# Use ZADD with score = priority * weight
score = tenant_priority.priority * tenant_priority.weight
redis.zadd(queue_key, {tenant_id: score})
# Try to dequeue immediately (if at front and capacity available)
# ... implementation
# If can't process immediately, wait with timeout
# ... implementation
4. Hotspot Detection & Mitigation
Hotspot Metrics Table
CREATE TABLE tenant_hotspots (
id BIGSERIAL PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
resource_type VARCHAR(50) NOT NULL, -- 'table', 'index', 'column', 'query'
resource_name VARCHAR(255) NOT NULL, -- table name or query hash
metric_type VARCHAR(50) NOT NULL, -- 'reads', 'writes', 'cpu', 'io', 'conflicts'
value DOUBLE PRECISION NOT NULL,
percentile DOUBLE PRECISION NOT NULL, -- 95th, 99th percentile
detected_at TIMESTAMP DEFAULT NOW(),
resolved_at TIMESTAMP,
severity VARCHAR(20) CHECK (severity IN ('low', 'medium', 'high', 'critical')),
metadata JSONB DEFAULT '{}'
);
CREATE INDEX idx_hotspots_tenant_detected ON tenant_hotspots(tenant_id, detected_at DESC);
CREATE INDEX idx_hotspots_resource ON tenant_hotspots(resource_type, resource_name);
Real-time Monitoring Query
-- Detect hotspots using pg_stat_statements
INSERT INTO tenant_hotspots (tenant_id, resource_type, resource_name,
metric_type, value, percentile, severity, metadata)
SELECT
current_setting('app.current_tenant_id')::UUID as tenant_id,
'query' as resource_type,
queryid as resource_name,
'total_time' as metric_type,
total_exec_time as value,
0.99 as percentile,
CASE
WHEN calls_per_second > 100 THEN 'critical'
WHEN calls_per_second > 50 THEN 'high'
WHEN calls_per_second > 10 THEN 'medium'
ELSE 'low'
END as severity,
jsonb_build_object(
'calls', calls,
'rows', rows,
'shared_blks_hit', shared_blks_hit,
'local_blks_written', local_blks_written
) as metadata
FROM pg_stat_statements
WHERE queryid IN (
SELECT queryid FROM pg_stat_statements
WHERE calls_per_second > 10 -- Threshold
ORDER BY total_exec_time DESC
LIMIT 10
);
Hotspot Mitigation Strategies
class HotspotMitigator:
def __init__(self):
self.redis = Redis()
async def detect_and_mitigate(self, tenant_id: str):
"""
Main hotspot detection and mitigation loop
"""
hotspots = await self._get_active_hotspots(tenant_id)
for hotspot in hotspots:
if hotspot.severity == 'critical':
await self._apply_emergency_measures(tenant_id, hotspot)
elif hotspot.severity == 'high':
await self._throttle_resource(tenant_id, hotspot.resource_name)
elif hotspot.severity == 'medium':
await self._log_and_notify(tenant_id, hotspot)
async def _apply_emergency_measures(self, tenant_id: str, hotspot):
"""
1. Temporarily reduce tenant's resource tokens
2. Redirect to read replicas
3. Cache aggressive caching
4. Notify admin
"""
# 1. Reduce token bucket rate
await self._adjust_fairness_weights(tenant_id, factor=0.1)
# 2. Force read replica routing
await self._set_tenant_routing(tenant_id, force_replica=True)
# 3. Enable aggressive caching
await self._enable_caching(tenant_id, ttl=30)
# 4. Alert
await self._send_alert(tenant_id, hotspot, "emergency")
async def _throttle_resource(self, tenant_id: str, resource_name: str):
"""
Apply per-table throttling
"""
# Reduce quota temporarily
await self._temporary_quota_reduction(
tenant_id,
resource_type='api_requests',
reduction_factor=0.5,
duration_minutes=30
)
5. Integration Layer & Middleware Stack
Complete Middleware Pipeline
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
class TenantIsolationMiddleware(BaseHTTPMiddleware):
def __init__(self, app):
super().__init__(app)
self.quota_manager = QuotaManager()
self.fairness_manager = FairnessManager()
self.hotspot_detector = HotspotDetector()
async def dispatch(self, request: Request, call_next):
# 1. Extract tenant ID (from JWT, subdomain, header)
tenant_id = self._extract_tenant_id(request)
if not tenant_id:
return Response("Invalid tenant", status_code=400)
# 2. Set database context
await self._set_db_tenant_context(tenant_id)
# 3. Check tenant status
if not await self._is_tenant_active(tenant_id):
return Response("Tenant suspended", status_code=403)
# 4. Fairness check
resource_pool = self._determine_resource_pool(request)
if not await self.fairness_manager.acquire_token(
tenant_id, resource_pool
):
return Response("Rate limited - fairness constraint",
status_code=429)
# 5. Quota check
resource_type = self._map_to_quota_resource(request)
if not await self.quota_manager.check_quota(
tenant_id, resource_type
):
return Response("Quota exceeded", status_code=429)
# 6. Process request
response = await call_next(request)
# 7. Record metrics for hotspot detection
await self._record_request_metrics(tenant_id, request, response)
# 8. Async hotspot analysis
asyncio.create_task(
self.hotspot_detector.analyze_recent_requests(tenant_id)
)
return response
Tenant Configuration Service
class TenantConfigService:
"""
Central service for tenant-specific configurations
"""
def __init__(self):
self.cache = TTLCache(maxsize=10000, ttl=300)
async def get_tenant_limits(self, tenant_id: str) -> dict:
cache_key = f"tenant_limits:{tenant_id}"
cached = self.cache.get(cache_key)
if cached:
return cached
limits = await self._fetch_from_db(tenant_id)
self.cache[cache_key] = limits
return limits
async def adjust_fairness_weights(self, tenant_id: str,
adjustment: dict):
"""
Dynamically adjust fairness weights based on behavior
"""
current = await self.get_tenant_fairness_profile(tenant_id)
# Increase weight for noisy tenants (reduces their share)
if adjustment.get('increase_priority'):
current['weight'] *= 0.8
else:
current['weight'] *= 1.1
await self._save_fairness_profile(tenant_id, current)
await self._broadcast_config_change(tenant_id)
6. Monitoring & Alerting
Key Metrics to Track
per_tenant:
- requests_per_second
- error_rate
- p95_latency
- resource_utilization (cpu, memory, io)
per_resource:
- hot_tables (reads/writes per second)
- large_queries (long running)
- full_table_scans
- lock_conflicts
system:
- total_tenant_count
- quota_violations
- fairness_violations
- hotspot_count
Grafana Dashboard Definition
{
"dashboard": {
"title": "Tenant Isolation Monitor",
"panels": [
{
"title": "Tenant API Usage",
"type": "timeseries",
"targets": [{
"expr": "sum(rate(api_requests_total{tenant=~\"$tenant\"}[5m])) by (tenant)",
"legend": "{{tenant}}"
}]
},
{
"title": "Hotspot Detection",
"type": "table",
"targets": [{
"expr": "tenant_hotspots{severity=~\"high|critical\", tenant=\"$tenant\"}",
"format": "table"
}]
}
]
}
}
7. Deployment & Configuration
Environment Variables
# Tenant Isolation Settings
TENANT_ISOLATION_ENABLED=true
TENANT_DEFAULT_QUOTA_STORAGE=1073741824 # 1GB
TENANT_DEFAULT_QUOTA_REQUESTS=10000
TENANT_FAIRNESS_ENABLED=true
TENANT_HOTSPOT_DETECTION_INTERVAL=300 # 5 minutes
TENANT_QUOTA_WARNING_THRESHOLD=0.8 # 80% warning
# Database
DATABASE_RLS_ENABLED=true
DATABASE_CONNECTION_POOL_SIZE_PER_TENANT=5
# Redis
REDIS_QUOTA_HOST=redis-quota.internal
REDIS_FAIRNESS_HOST=redis-fairness.internal
Kubernetes Configuration
apiVersion: apps/v1
kind: Deployment
metadata:
name: tenant-isolation-service
spec:
replicas: 3
template:
spec:
containers:
- name: isolation
image: tenant-isolation:latest
env:
- name: TENANT_ISOLATION_ENABLED
value: "true"
resources:
limits:
memory: "512Mi"
cpu: "500m"
requests:
memory: "256Mi"
cpu: "100m"
# Sidecar for per-tenant connection pooling
- name: pgbouncer
image: pgbouncer:latest
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: tenant-isolation-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: tenant-isolation-service
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300
8. Emergency Procedures
Hotspot Emergency Playbook
1. **Detection**: Hotspot severity ≥ high detected
2. **Immediate Actions**:
- Reduce tenant's token bucket rate by 80%
- Force read replica routing
- Enable query result caching (5min TTL)
- Alert operations team
3. **Investigation**:
- Check: `SELECT * FROM tenant_hotspots WHERE tenant_id = ? AND resolved_at IS NULL`
- Analyze: `EXPLAIN (ANALYZE, BUFFERS) <problematic_query>`
- Review: `SELECT * FROM pg_locks WHERE pid = <offending_pid>`
4. **Resolution**:
- If missing index → CREATE INDEX CONCURRENTLY
- If bad query → Query rewrite or materialized view
- If design issue → Suggest schema changes to tenant
5. communicate**: Notify tenant of issue and mitigation steps
Key Design Principles
- Defense in Depth: Multiple layers (RLS, middleware, database) ensure isolation
- Graceful Degradation: When quotas exceeded, degrade gracefully rather than crash
- Observability: Every component emits metrics/logs for troubleshooting
- Automation: Auto-mitigation for common hotspots
- Fairness Not Equality: Different tenants get different shares based on plan/criticality
- No Single Point of Failure: Each isolation component can fail independently
Testing Strategy
- Unit Tests: Each isolation component independently
- Integration Tests: Full stack with multiple tenants
- Chaos Tests:
- Simulate noisy neighbor (one tenant hammering DB)
- Test quota enforcement under load
- Simulate hotspot scenarios
- Security Tests: Attempt cross-tenant access bypasses
This design provides comprehensive tenant isolation while maintaining performance and fairness. The system can handle:
- ✅ RLS: Database-level row filtering
- ✅ Quotas: Real-time tracking and enforcement
- ✅ Fairness: Token buckets + WFQ prevents noisy neighbors
- ✅ Hotspots: Detection + automated mitigation
- ✅ Scalability: Per-tenant connection pools, caching, read replicas
- ✅ Observability: Full metrics, logs, and alerts
The implementation can be adapted to different databases (PostgreSQL, MySQL with proxies, etc.) and cloud providers.