I've started by breaking down the project request. My goal is to design a REST API that's scalable, using Node.js and Express. I'm focusing on multi-tenant authentication and rate limiting as the core features. Next, I need to map out the data models.
Architecting API Components
I'm now diving into the architectural details. Thinking about how the API should handle scalability, I've considered statelessness using JWTs, caching with Redis, and the implications of horizontal scaling. For multi-tenancy, I'm leaning toward a discriminator column approach in the database, while acknowledging other options. I'm also planning the authentication with JWTs including tenant info, and the rate-limiting strategy using Redis.
Outlining Implementation Steps
I'm solidifying the steps now. First, setting up the foundation: the entry point and environment variables. Next, I'll integrate Redis for caching and rate limiting. I am also working on the multi-tenancy middleware that will identify the tenant using a header. After this I can focus on authentication, rate limiting middleware, and finally, I can build example API routes.
Detailing the Implementation
I'm now zeroing in on the practical coding steps. I've sketched the multi-tenancy middleware with header-based tenant identification. The next step involves solidifying the authentication middleware, including JWT verification. I am also working on the rate-limiting setup, considering both tenant and potentially user-specific limits, utilizing the Redis infrastructure. After that, I will construct some basic API routes, for example, to test the authentication and tenant isolation.
Planning Route Implementations
I'm now detailing the implementation, and I'm mapping out the key API routes and how they interact with the middleware. I'm prioritizing the multi-tenancy layer's integration, alongside the authentication and rate-limiting. I need to make sure I am clarifying the separation of concerns and database access patterns. Lastly, I'll be focusing on edge cases, such as the handling of users and tenants.
Synthesizing Architectural Choices
I've considered various architecture and design choices. For scalability, I'm leaning heavily on statelessness via JWTs, caching with Redis, and the potential for horizontal scaling. I'm going with a discriminator column approach for multi-tenancy, and am finalizing the JWT structure to include tenant information, with Redis-based rate limiting. I also need to refine how users will be handled within a multi-tenant environment, especially if a user belongs to multiple tenants.
This is a comprehensive design and implementation guide for a scalable, multi-tenant REST API using Node.js, Express, and Redis.
Architecture Overview
To ensure scalability, we will adhere to the Stateless principle.
Multi-tenancy Strategy: We will use Logical Isolation (Discriminator column) combined with strict middleware context enforcement. For higher security/scale, this can be swapped for Schema-based isolation without changing the API interface.
Rate Limiting: We will use a Distributed Token Bucket algorithm backed by Redis. This allows the rate limiter to work across multiple Node.js instances/servers.
/src
/config
redis.js # Redis connection
db.js # Database connection
/middlewares
tenant.js # Identifies tenant context
auth.js # Validates JWT and Tenant match
rateLimit.js # Redis-based rate limiter
/models
User.js # Example User model with tenantId
/routes
api.js # Route definitions
app.js # App setup
server.js # Entry point
2. Configuration & Infrastructure
src/config/redis.js
Redis is crucial here. It handles the state for rate limiting so that if you scale your Node app to 10 instances, they all share the same hit counters.
src/middlewares/rateLimit.js
We use rate-limiter-flexible which offers atomic increments in Redis. This prevents race conditions under high load.
javascript
const { RateLimiterRedis } = require('rate-limiter-flexible');
const redisClient = require('../config/redis');
// Configuration: 20 requests per minute per tenant/user
const rateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'middleware',
points: 20, // Number of requests
duration: 60, // Per 60 seconds
});
const rateLimitMiddleware = async (req, res, next) => {
try {
// Rate limit key strategy:
// 1. If authenticated: limit by TenantID + UserID
// 2. If public: limit by IP + TenantID (if present)
const tenantId = req.tenantId || 'default';
const userId = req.user ? req.user.id : req.ip;
const key = `${tenantId}:${userId}`;
await rateLimiter.consume(key);
next();
} catch (rejRes) {
res.status(429).json({
error: 'Too Many Requests',
message: `Rate limit exceeded for tenant context. Try again later.`
});
}
};
module.exports = rateLimitMiddleware;
4. Multi-Tenancy Middleware
src/middlewares/tenant.js
This middleware extracts the context. We will use the X-Tenant-ID header. In a real scenario, you might look up subdomain mapping in Redis to valid UUIDs.
javascript
const tenantResolver = (req, res, next) => {
const tenantId = req.headers['x-tenant-id'];
if (!tenantId) {
return res.status(400).json({ error: 'Missing X-Tenant-ID header' });
}
// OPTIONAL: Validate if tenantId exists in your Cache/DB here.
// const isValid = await redisClient.sismember('tenants', tenantId);
// if(!isValid) throw error...
// Attach to request object so strictly used downstream
req.tenantId = tenantId;
next();
};
module.exports = tenantResolver;
5. Authentication Middleware
src/middlewares/auth.js
We verify the JWT and ensure the user belongs to the Tenant requested in the header.
javascript
const jwt = require('jsonwebtoken');
const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// CRITICAL: Security check
// Ensure the token issued for this user allows access to the requested tenant
if (decoded.tenantId !== req.tenantId) {
return res.status(403).json({ error: 'Access denied for this tenant' });
}
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
};
module.exports = authMiddleware;
6. Data Layer (Example Logic)
src/models/User.js (Conceptual Mongoose Schema)
Every query must include the tenantId.
server.js
To handle scale on a single machine, we use Node's Cluster module. For cloud deployment (AWS/K8s), you would typically use Docker replicas instead of the cluster module, but this demonstrates local scalability.
javascript
const app = require('./src/app');
const http = require('http');
const cluster = require('cluster');
const os = require('os');
const PORT = process.env.PORT || 3000;
const numCPUs = os.cpus().length;
if (process.env.NODE_ENV === 'production' && cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers based on CPU cores
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Restarting...`);
cluster.fork();
});
} else {
// Worker implementation
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Worker ${process.pid} started on port ${PORT}`);
});
}
Summary of Scalability Features
State stored in Redis: The Rate Limiter logic is decoupled from the Node process memory. If you spin up 50 containers in Kubernetes, they all talk to the same Redis instance (or Redis Cluster) to maintain accurate rate limits.
Context Middleware: Tenant ID is resolved before hitting controllers. This prevents developers from accidentally querying data without the tenantId filter.
Clustering: Utilizes all available CPU cores.
Database Indexing: The Schema example enforces Compound Indexes (tenantId + field), which is essential for query performance in a shared-database multi-tenant architecture.
Usage Flow
Client: Sends POST /api/login with Header X-Tenant-ID: tenant_abc.
API: Validates credentials in DB where tenantId == tenant_abc. Returns JWT containing tenantId: tenant_abc.
Client: Sends GET /api/resource with Headers Authorization: Bearer ... and X-Tenant-ID: tenant_abc.
RateLimit Middleware: Checks Redis key ratelimit:tenant_abc:user_123. If < 20, increment and proceed.
Auth Middleware: Decodes JWT. Checks if jwt.tenantId === header.tenantId.