We are going to design a per-request isolation mechanism that includes:
- CPU and memory caps (using cgroups or containers, but note: we are at application level, so we might use thread-based or coroutine-based isolation with resource monitoring)
- I/O caps (limiting the amount of I/O operations or bytes read/written)
- Backpressure (when the system is overloaded, we want to slow down or reject new requests)
- Shedding (dropping requests when the system is too busy)
However, note that we are in an application-level context (like a server process) and we cannot use OS-level containers for each request (that would be too heavy).
Instead, we can use a combination of:
- For CPU: We can track the amount of CPU time used by a request (using thread CPU time or coroutine CPU time if we have a way to measure). But note: in a multi-threaded server, we might not have per-request CPU accounting easily. Alternatively, we can use a fixed number of worker threads and assign requests to workers, then track per-worker? Not exactly per-request.
Alternatively, we can use a token bucket for CPU time: each request is allocated a fixed amount of CPU time (in milliseconds) and if it exceeds, it is terminated or slowed down.
But note: we are in a cooperative multitasking environment (like asyncio) or preemptive (threads).
Let's assume we are in an asynchronous server (like asyncio). Then:
- We can run each request in a separate task and use
asyncio.wait_for to set a timeout for the entire request? That's more about time than CPU.
However, we want to limit CPU usage, not just wall time. We can try to measure the CPU time used by a task? In Python, we can use resource.getrusage but that is per process. We can use time.process_time but that is also per process and not per task.
Alternatively, we can use a fixed number of worker threads/processes and assign requests to them, then use OS-level mechanisms (like cgroups) for each worker? That might be heavy.
Given the complexity, perhaps we focus on:
-
Memory: We can set a hard limit on the amount of memory a request can allocate? This is tricky because we are in the same process. We can use a custom allocator that tracks per-request? That's very heavy.
-
I/O: We can limit the number of I/O operations (like database queries, file reads) per request? We can set a maximum number of I/O operations or bytes read/written.
-
Backpressure: We can use a queue for incoming requests and when the queue is full, we reject or slow down.
-
Shedding: When the system is overloaded (e.g., CPU or memory high), we start rejecting requests.
However, the problem asks for per-request isolation, meaning each request should not be able to starve the system of resources.
Let's break down:
Option 1: Use separate processes (or containers) for each request. This is the most isolated but highest overhead. Not feasible for high QPS.
Option 2: Use a fixed thread pool and assign each request to a thread, then use OS-level resource limits (like setrlimit) for that thread? But setrlimit is per process, not per thread.
Option 3: Use a cooperative model where each request yields periodically and we check the resources used.
Given the constraints, we might have to settle for:
- Per-request timeouts (to prevent infinite loops or long running requests)
- Per-request memory limits (if we can track memory allocations per request, which is hard in a shared heap)
- I/O limits: We can count the number of I/O operations (like database queries, file opens) and set a limit.
Alternatively, we can design the system such that each request is handled by a separate worker (thread or process) and then we can use OS-level resource limits for that worker?
For example, in a thread-per-request model, we can set the CPU affinity and use cgroups for the entire process? That doesn't isolate per request.
Given the complexity, perhaps we should think of a simplified model:
We are going to design a middleware that:
-
For each request, we create a context that tracks:
- CPU time used (if we can measure per task, otherwise we skip)
- Memory allocated (if we can track, otherwise skip)
- I/O operations count and bytes read/written.
-
We set limits for each of these.
-
If a request exceeds a limit, we terminate it (or raise an exception and return an error).
-
We also have a global system monitor that checks overall system load (CPU, memory, I/O) and if the system is overloaded, we start shedding requests (rejecting new ones) or applying backpressure (slowing down acceptance).
However, note that in an async server, we can have many requests in flight, but they are all in the same process and share the same memory and CPU.
So, how to track per-request memory? We can use a custom allocator? That's very heavy and not standard.
Alternatively, we can design the application such that each request is handled in a separate process (or container) and then we can use cgroups to limit resources. This is the way to go for strong isolation.
But the problem says "per-request isolation budget", and we are in an application context? Maybe we are to design a system that uses containers (like Docker) or processes for each request? That would be like a serverless function.
Let's assume we are to design a system that runs each request in an isolated environment (like a container) and then we can set:
- CPU limit (e.g., 0.1 CPU core)
- Memory limit (e.g., 100MB)
- I/O limit (e.g., 10MB read, 10MB write)
Then, we can use the container runtime (like Docker) to set these limits.
But what about backpressure and shedding? We can have a front-facing load balancer that:
- Monitors the overall system load (number of running containers, CPU, memory, etc.)
- If the system is overloaded, it can start rejecting requests (shedding) or slowing down the rate of new containers (backpressure).
Alternatively, we can have a queue of requests and when the queue is full, we reject.
But note: the problem says "per-request isolation budget", so we are focusing on the per-request resource limits, and then also having system-level backpressure and shedding.
So, design:
- Request comes in.
- We create a container (or process) for that request with resource limits (CPU, memory, I/O).
- We run the request in that container.
- We have a global monitor that checks:
- Total number of containers running (to avoid too many context switches or memory pressure)
- Overall system CPU and memory usage.
- If the system is overloaded (e.g., 80% CPU used, 90% memory used, or too many containers), then we start shedding: we reject new requests or we slow down the creation of new containers (backpressure).
However, creating a container per request is heavy. We can use a pool of containers? But then we are not isolating per request because the container might be reused and the budget would be for the container's lifetime, not per request.
Alternatively, we can use a process pool and set resource limits per process? But then we have to reset the limits for each request? And we cannot have multiple requests in the same process because they would share the same resource limits.
So, we are back to one request per container/process.
Given the overhead, this is suitable for long-running or resource-intensive requests, not for high QPS small requests.
But the problem does not specify the workload.
Let's assume we are to design a system that can run arbitrary code (like a function as a service) and we want to isolate each function invocation.
Then:
-
Use a container runtime (like Docker) or a sandbox (like gVisor) to run each request in a separate container with resource limits.
-
We have a front-end that receives requests and dispatches them to workers (which create and manage containers).
-
The front-end also implements backpressure and shedding:
- It has a maximum number of concurrent containers it can run (based on system capacity).
- It uses a queue for incoming requests. If the queue is full, it rejects (shedding) or returns a "try again" (backpressure).
-
We can also set per-request limits in the container (CPU shares, memory limit, blkio limit).
-
The container is destroyed after the request is done.
This is the typical serverless architecture.
But note: the problem says "per-request isolation budget", so we are setting the budget (the limits) for each request.
How to set the budget? The request might come with its own budget? Or we set a default budget? Or the client specifies?
Let's assume the client can specify the budget (or we have a default). Then:
-
The front-end receives a request with a desired CPU, memory, I/O.
-
It checks if the requested budget is within the system's allowed limits (so a request cannot ask for too much).
-
Then it creates a container with those limits.
-
If the system is too busy, it might reject the request (shedding) or queue it (with a timeout) for backpressure.
So, the design:
Components:
-
Front-end (load balancer) that:
- Accepts requests.
-Authenticates and validates the request (including the resource budget requested).
- Checks system capacity and current load.
- If the system can accommodate, it dispatches to a worker (or creates a container itself) and returns a token orID to the client to check status.
- If the system is overloaded, it can:
a) Reject the request immediately (shedding).
b) Queue the request with a timeout (backpressure) and then process when resources free up.
-
Worker (or container manager) that:
- Creates a container with the specified resource limits (using Docker or similar).
- Runs the request code in the container.
- Monitors the container for resource usage (if needed, we can kill if it exceeds? But the container runtime already enforces limits).
- Returns the result to the front-end (or stores it for the client to retrieve).
-
System monitor that:
- Collects metrics: CPU, memory, I/O, number of containers, etc.
- Feeds into the front-end's decision on shedding/backpressure.
However, note: the container runtime already enforces the per-container limits. So the isolation is at the container level.
But what if the request code tries to do something that the container cannot (like fork bomb)? The container's resource limits will kill it when it exceeds.
So we have:
Per-request isolation: via container with limits.
Backpressure: by controlling the rate of new containers (or queueing).
Shedding: by rejecting when system is overloaded.
But note: the container creation is heavy. We can use a pool of pre-created containers? But then we cannot set per-request limits dynamically? We can set the limits when we run the container? Actually, Docker allows setting limits at run time.
Alternatively, we can have a pool of containers with fixed limits? Then we cannot have per-request different budgets.
So, if we want per-request different budgets, we have to create a new container each time with the requested limits.
We can also have a set of pre-created containers with different fixed budgets (like small, medium, large) and then assign the request to the appropriate container type? That would reduce creation overhead.
But then we are not fully flexible.
Given the trade-offs, let's assume we create a new container for each request with the requested limits (within system allowed max).
Steps:
-
Request comes with:
- code (or function to run)
- input
- resource budget: cpu (in cores or shares), memory (in MB), I/O (in MB for read/write, or IOPS)
-
Validate the budget: each must be below the system's maximum per request.
-
Check system load:
- If current number of containers < max_containers and system resources (CPU, memory) are below threshold (e.g., 80%), then accept.
- Else, reject (shedding) or queue (backpressure) for a limited time.
-
If accepted, create a container with the specified limits.
-
Run the code in the container.
-
Collect the result and destroy the container.
We can also have a timeout for the request (wall time) to prevent hanging.
This design is similar to AWS Lambda or Google Cloud Functions.
However, note that the problem does not specify the environment. We are just asked to create a per-request isolation budget with CPU/mem/IO caps, backpressure, and shed.
So, we can describe it in terms of:
- Isolation: using containers (or processes) with resource limits.
- Backpressure: by having a queue and controlling the rate of container creation.
- Shedding: by rejecting when system is overloaded.
But if we are not to use containers, then we have to do it at the application level, which is much harder.
Given the complexity of per-request resource tracking in a shared process, I think the intended answer is to use containers.
Let me summarize:
Proposed solution:
-
Use a container-based isolation for each request, setting CPU, memory, and I/O limits via container runtime (e.g., Docker).
-
Implement a front-end that:
- Receives requests with desired resource budgets.
- Validates budgets against system policies.
- Monitors system load (containers count, CPU, memory, I/O).
- Applies backpressure by queuing requests when the system is somewhat loaded (but not yet overloaded) and shedding by rejecting when the system is overloaded.
-
Workers that manage the container lifecycle: create, run, destroy.
-
Optional: per-request timeout (wall time) to avoid long running requests.
This provides strong isolation and meets the requirements.
If we cannot use containers, then we have to rely on:
-
Running each request in a separate process (still heavy) and using setrlimit for that process? But then we have to fork for each request? That's similar to containers but without the isolation of the filesystem and network.
-
Or, in a multi-threaded server, we can use thread CPU affinity and set limits? But again, setrlimit is per process.
So, without containers, we cannot have per-request I/O limits (blkio) and memory limits (unless we use a separate process).
Therefore, I think the container-based approach is the way to go.
Let's write the answer accordingly.
To implement per-request isolation with resource caps, backpressure, and shedding, you need a multi-layered approach combining kernel-level enforcement (for strong isolation) and application-level controls (for agility). Below is a practical design:
1. Isolation Budget per Request
A. Kernel-Level Enforcement (Strong Isolation)
Use cgroups v2 (Linux) or containers (Docker, Firecracker) for hard limits. Each request runs in its own lightweight sandbox (e.g., a container or systemd-nspawn).
Typical cgroup settings:
# CPU: Limit to 0.1 cores (10% of one core)
cpu.max=10000 # 10ms of CPU time per 100ms period
# Memory: Hard limit + swap limit
memory.max=100M
memory.swap.max=0
# I/O: Read/write bandwidth limits (if supported)
io.max=b8:1 rbps=1M wbps=1M # For block device 8, 1MB/s read/write
How to apply per-request:
- Each request gets a unique cgroup path (e.g.,
/sys/fs/cgroup/request-<uuid>).
- The request’s process/thread is moved into that cgroup via
clone() with CLONE_NEWCGROUP or by writing its PID to cgroup.procs.
- Tools: Docker (
--cpus, --memory, --device-read-bps), Kata Containers, or custom runtime using libcgroup.
Note: For high QPS, container creation overhead may be prohibitive. Use cgroup direct assignment without full containerization if security allows (same kernel, separate cgroups).
B. Application-Level Enforcement (Soft Limits)
If kernel isolation is too heavy, track and throttle within the app:
-
CPU: Use setitimer(ITIMER_VIRTUAL) or cputimer in async runtimes (e.g., Tokio’s tokio::time::sleep_until for cooperative yielding).
Example (Rust async):
let start = std::time::Instant::now();
let cpu_budget = Duration::from_millis(100); // 100ms CPU time
loop {
if start.elapsed() > cpu_budget {
return Err(RequestBudgetExceeded);
}
// ... do work ...
tokio::task::yield_now().await; // Yield periodically
}
-
Memory: Use a custom allocator (e.g., jemalloc with per-request arenas) or track allocations manually (heavy).
Alternative: Run request in a separate process (not thread) and use setrlimit(RLIMIT_AS).
-
I/O: Wrap sockets/files with counters. Reject/block when bytes exceed budget.
Example (Python async):
class BudgetedIO:
def __init__(self, stream, max_bytes):
self.stream = stream
self.bytes_read = 0
self.max_bytes = max_bytes
async def read(self, n):
if self.bytes_read + n > self.max_bytes:
raise IOBudgetExceeded
data = await self.stream.read(n)
self.bytes_read += len(data)
return data
2. Backpressure Mechanism
Goal: Slow down request acceptance when system load is high (before limits are hit).
Implementation:
-
Token Bucket per Request Type:
- Each request type has a max concurrency (e.g., 50 concurrent “heavy” requests).
- Acquire a token before processing; release after.
- Tokens refill at a fixed rate.
-
Dynamic Queueing:
- Use a bounded queue for incoming requests (e.g., 1000 pending max).
- When queue is full, return
429 Too Many Requests or 503 Service Unavailable with Retry-After.
-
Feedback to Load Balancer:
- Expose
/health endpoint with current load metrics.
- Load balancer (e.g., Envoy, HAProxy) uses this to adjust routing or reject.
Example (Redis-based token bucket):
import redis
r = redis.Redis()
def can_accept(request_type):
key = f"tokens:{request_type}"
# Use Redis INCR with TTL for refill
current = r.incr(key)
if current == 1:
r.expire(key, 60) # Refill every 60s
return current <= MAX_CONCURRENT[request_type]
3. Shedding (Overload Protection)
Goal: Drop requests aggressively when system is critically overloaded.
Triggers:
- System-wide: CPU > 90% for 30s, memory > 85%, or paging active.
- Per-service: Error rate > 5%, latency > 2× SLA.
- Per-request-type: Concurrency > 2× typical peak.
Strategies:
- Random Shedding: Drop % of requests randomly when overload threshold crossed.
- Priority-based: Assign priority to requests (e.g., paid users > free). Shed low-priority first.
- Client Identifier: Shed based on client IP/user-agent (e.g., scrapers).
Implementation:
def should_shed():
if system_cpu_usage() > 0.9 or memory_pressure():
# Randomly shed 20% of requests
return random.random() < 0.2
return False
# In request handler:
if should_shed():
return Response(status=503, body="Overloaded")
4. Full Architecture Flow
Client → Load Balancer → Admission Control → Queue → Worker (with per-request cgroup) → Response
Steps:
-
Admission Control (in LB or API gateway):
- Validate request budget (client-specified or default).
- Check global shedding flag/load.
- Apply backpressure: if system load > 70%, delay acceptance (return
429 or slow retry).
- If accepted, assign a unique
request_id and enqueue.
-
Worker:
- Dequeue request.
- Create cgroup for
request_id with requested CPU/mem/IO caps.
- Spawn process/thread in that cgroup.
- Track I/O counters (using seccomp/bpf or app-level wrappers).
- Enforce timeouts (wall-clock + CPU-time).
- On exit, destroy cgroup, log metrics.
-
Monitoring:
- Per-request: CPU time, memory peak, I/O bytes, duration.
- System: cgroup count, system load, queue length.
- Feed metrics to shedding/backpressure logic.
5. Trade-offs & Considerations
| Aspect | Kernel Isolation | App-Level |
|---|
| Overhead | High (cgroup/container setup) | Low (just counters) |
| Accuracy | Exact (kernel-enforced) | Approximate (cooperative) |
| Security | Strong (kernel namespaces) | Weak (same process memory) |
| I/O Control | Excellent (blkio cgroup) | Limited (can’t block device I/O) |
| Use Case | Multi-tenant, untrusted code | Single-tenant, trusted code |
Recommendation:
- Untrusted/multi-tenant: Use cgroups/containers per request.
- High QPS trusted: App-level limits + process-per-request (fork) with
setrlimit.
- Hybrid: Critical requests containerized; others app-level.
6. Example Stack
- Container Runtime: Docker, containerd, Firecracker (microVMs).
- Orchestration: Kubernetes with
RuntimeClass for different isolation levels.
- Backpressure/Shedding: Envoy with
overload action, or custom middleware.
- Metrics: Prometheus + cAdvisor (for cgroup metrics), or custom app metrics.
- Language Support:
- Rust:
nix crate for cgroups, tokio for async limits.
- Go:
golang.org/x/sys/unix for cgroups, context timeouts.
- Java: JVM not ideal for per-request CPU limits; use containers.
7. Quick Start (Linux cgroups v2)
# 1. Create cgroup
sudo mkdir /sys/fs/cgroup/request-123
# 2. Set limits
echo "10000" | sudo tee /sys/fs/cgroup/request-123/cpu.max # 10% CPU
echo "100M" | sudo tee /sys/fs/cgroup/request-123/memory.max # 100MB RAM
# 3. Run process in cgroup
sudo systemd-run --scope -p "Delegate=yes" -p "CPUQuota=10%" -p "MemoryMax=100M" your-command
# 4. Monitor
sudo cat /sys/fs/cgroup/request-123/cpu.stat
sudo cat /sys/fs/cgroup/request-123/memory.current
Key Takeaway: The strongest isolation comes from kernel-enforced cgroups/containers, but for high throughput, combine with application-level throttling and dynamic shedding/backpressure based on real-time metrics. Always set hard timeouts (wall-clock) to prevent runaway requests.