@sinkaroid/rust-shapeshift 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/bin/rust-shapeshift.js +29 -0
- package/package.json +45 -4
- package/skills/rust-shapeshift/SKILL.md +282 -0
- package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +122 -0
- package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +139 -0
- package/skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md +83 -0
- package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +158 -0
- package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +145 -0
- package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +105 -0
- package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +147 -0
- package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +122 -0
- package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +121 -0
- package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +126 -0
- package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +170 -0
- package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +158 -0
- package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +115 -0
- package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +157 -0
- package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +143 -0
- package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +192 -0
- package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +117 -0
- package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +255 -0
- package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +113 -0
- package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +135 -0
- package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +146 -0
- package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +145 -0
- package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +207 -0
- package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +125 -0
- package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +125 -0
- package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +169 -0
- package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +253 -0
- package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +94 -0
- package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +140 -0
- package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +251 -0
- package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +230 -0
- package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +130 -0
- package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +108 -0
- package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +156 -0
- package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +134 -0
- package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +97 -0
- package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +170 -0
- package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +149 -0
- package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +124 -0
- package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +254 -0
- package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +114 -0
- package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +130 -0
- package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +99 -0
- package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +159 -0
- package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +109 -0
- package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +104 -0
- package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +156 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# Jemalloc Tuning, Custom Allocators, and Heap Profiling
|
|
2
|
+
|
|
3
|
+
Under sustained high-concurrency async workloads in Linux containers, the default GNU C library (`glibc`) allocator suffers from arena fragmentation, refusing to release unmapped memory back to the kernel. Switching to `jemalloc` or `mimalloc` and enabling active heap profiling prevents memory bloat and pinpoints allocation leaks.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. When to Switch Allocators
|
|
8
|
+
|
|
9
|
+
| Feature | GNU `glibc` | `tikv-jemallocator` | `mimalloc` |
|
|
10
|
+
| :--- | :--- | :--- | :--- |
|
|
11
|
+
| **Arena Management** | Dynamic per-thread, fragmentation-prone | Strict bins, decay-based purging | Page-based segment allocator |
|
|
12
|
+
| **Long-Running RSS Stability** | Poor without `malloc_trim` | Exceptional under heavy churn | Exceptional |
|
|
13
|
+
| **Multi-Thread Scalability** | Moderate | High (thread-cache arena) | Extremely High |
|
|
14
|
+
| **Runtime Heap Profiling** | Complex (`valgrind`) | Built-in via `jemalloc_ctl` | Basic |
|
|
15
|
+
| **Best For** | Minimal dependencies | Production servers, web backends | CPU-bound batch tasks |
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## 2. Drop-in `tikv-jemallocator` Configuration
|
|
20
|
+
|
|
21
|
+
Add `tikv-jemallocator` to `Cargo.toml`:
|
|
22
|
+
```toml
|
|
23
|
+
[dependencies]
|
|
24
|
+
tikv-jemallocator = { version = "0.6", features = ["profiling", "unprefixed_malloc_on_supported_platforms"] }
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
In your `main.rs`:
|
|
28
|
+
```rust
|
|
29
|
+
#[cfg(not(target_env = "msvc"))]
|
|
30
|
+
use tikv_jemallocator::Jemalloc;
|
|
31
|
+
|
|
32
|
+
#[cfg(not(target_env = "msvc"))]
|
|
33
|
+
#[global_allocator]
|
|
34
|
+
static GLOBAL: Jemalloc = Jemalloc;
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 3. Production Runtime Environment Tuning
|
|
40
|
+
|
|
41
|
+
Configure jemalloc via the `MALLOC_CONF` environment variable in your `Dockerfile` or container runtime:
|
|
42
|
+
|
|
43
|
+
```dockerfile
|
|
44
|
+
# Active background purging and aggressive page release
|
|
45
|
+
ENV MALLOC_CONF="background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- `background_thread:true`: Enables dedicated jemalloc background worker threads to sweep and purge unused arenas without stalling application tasks.
|
|
49
|
+
- `dirty_decay_ms:1000`: Decays dirty (unused) pages and frees them back to the OS kernel within 1 second.
|
|
50
|
+
- `muzzy_decay_ms:1000`: Decays muzzy pages (purged via `MADV_FREE`) within 1 second.
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## 4. On-Demand Live Heap Dump via `jemalloc-ctl`
|
|
55
|
+
|
|
56
|
+
You can trigger a live heap profile dump in production via an HTTP admin endpoint without restarting the process:
|
|
57
|
+
|
|
58
|
+
```rust
|
|
59
|
+
use axum::{response::IntoResponse, http::StatusCode};
|
|
60
|
+
|
|
61
|
+
#[cfg(not(target_env = "msvc"))]
|
|
62
|
+
pub async fn dump_heap_profile() -> impl IntoResponse {
|
|
63
|
+
use tikv_jemalloc_ctl::{epoch, prof};
|
|
64
|
+
use std::ffi::CString;
|
|
65
|
+
|
|
66
|
+
// Advance epoch to refresh jemalloc internal stats
|
|
67
|
+
let _ = epoch::advance();
|
|
68
|
+
|
|
69
|
+
let timestamp = std::time::SystemTime::now()
|
|
70
|
+
.duration_since(std::time::UNIX_EPOCH)
|
|
71
|
+
.unwrap_or_default()
|
|
72
|
+
.as_secs();
|
|
73
|
+
let file_path = format!("/tmp/heap_profile_{timestamp}.prof");
|
|
74
|
+
let c_path = CString::new(file_path.clone()).unwrap();
|
|
75
|
+
|
|
76
|
+
// Trigger heap profile dump
|
|
77
|
+
match prof::dump::write(c_path.as_c_str()) {
|
|
78
|
+
Ok(_) => (StatusCode::OK, format!("Heap profile dumped to {file_path}")),
|
|
79
|
+
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("Dump failed: {e}")),
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Analyze the resulting `.prof` file using `jeprof`:
|
|
85
|
+
```bash
|
|
86
|
+
jeprof --show_bytes --pdf ./target/release/my-service /tmp/heap_profile_1234567.prof > heap.pdf
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 5. Allocation Profiling in CI via DHAT
|
|
92
|
+
|
|
93
|
+
For deterministic regression testing in CI without jemalloc overhead, use `dhat` to catch unintended heap churn:
|
|
94
|
+
|
|
95
|
+
```toml
|
|
96
|
+
[dev-dependencies]
|
|
97
|
+
dhat = "0.3"
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
In your integration test:
|
|
101
|
+
```rust
|
|
102
|
+
#[test]
|
|
103
|
+
fn test_zero_allocations_on_hot_path() {
|
|
104
|
+
#[cfg(feature = "dhat-heap")]
|
|
105
|
+
let _profiler = dhat::Profiler::builder().testing().build();
|
|
106
|
+
|
|
107
|
+
let payload = b"GET /api/v1/health HTTP/1.1\r\n\r\n";
|
|
108
|
+
parse_request_zero_copy(payload);
|
|
109
|
+
|
|
110
|
+
#[cfg(feature = "dhat-heap")]
|
|
111
|
+
{
|
|
112
|
+
let stats = dhat::HeapStats::get();
|
|
113
|
+
// Assert that zero heap allocations occurred during parsing
|
|
114
|
+
assert_eq!(stats.total_blocks, 0, "Expected 0 allocations on hot path!");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 6. Alternative: `mimalloc` for Low Overhead
|
|
122
|
+
|
|
123
|
+
If heap profiling is not required and raw single-thread/multi-thread allocator speed is the goal:
|
|
124
|
+
|
|
125
|
+
```toml
|
|
126
|
+
[dependencies]
|
|
127
|
+
mimalloc = { version = "0.1", default-features = false }
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
In `main.rs`:
|
|
131
|
+
```rust
|
|
132
|
+
use mimalloc::MiMalloc;
|
|
133
|
+
|
|
134
|
+
#[global_allocator]
|
|
135
|
+
static GLOBAL: MiMalloc = MiMalloc;
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## 7. Production Checklist
|
|
141
|
+
|
|
142
|
+
- [ ] Evaluated target platform: default glibc vs `tikv-jemallocator` vs `mimalloc`.
|
|
143
|
+
- [ ] Injected `MALLOC_CONF="background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000"` in Docker container.
|
|
144
|
+
- [ ] Added live diagnostic heap dump endpoint protected by administrative authorization.
|
|
145
|
+
- [ ] Added DHAT heap assertion tests on latency-critical hot paths.
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Kubernetes Runtime and Resource Containment
|
|
2
|
+
|
|
3
|
+
Deploying Rust services to Kubernetes (K8s) introduces distinct orchestrator-level constraints that do not exist in standalone Docker. Misconfigurations in cgroups, worker thread counts, memory limits, probe design, or termination signals frequently cause unexpected CPU throttling, `OOMKilled (Exit Code 137)` terminations, and `502 Bad Gateway` errors during rolling deployments.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The CFS Quota & Tokio Thread Explosion Trap
|
|
8
|
+
|
|
9
|
+
### The Problem
|
|
10
|
+
In Kubernetes, pods define CPU limits using CFS (Completely Fair Scheduler) quotas (e.g., `resources.limits.cpu: "1"` or `"500m"`). However, the physical worker node may possess 64 or 128 physical vCPUs.
|
|
11
|
+
|
|
12
|
+
By default, `tokio::runtime::Builder::new_multi_thread()` or `#[tokio::main]` calls `std::thread::available_parallelism()`. In many Linux kernel / container configurations, this reads the **node's total CPU cores (128)** rather than the pod's quota. Spawning 128 Tokio worker threads inside a 1-core container causes:
|
|
13
|
+
1. Massive per-thread stack allocation (128 × thread stack size + per-thread glibc arenas).
|
|
14
|
+
2. Catastrophic context-switching thrashing.
|
|
15
|
+
3. Severe CFS bandwidth throttling, driving latency from milliseconds into seconds.
|
|
16
|
+
|
|
17
|
+
### The Solution: Quota-Aware Runtime Sizing
|
|
18
|
+
Explicitly cap Tokio worker threads based on container CPU limits or environment variables:
|
|
19
|
+
|
|
20
|
+
```rust
|
|
21
|
+
use std::env;
|
|
22
|
+
|
|
23
|
+
fn build_optimized_runtime() -> tokio::runtime::Runtime {
|
|
24
|
+
// Read from K8s downward API env (e.g., CONTAINER_CPU_LIMIT=2) or fallback
|
|
25
|
+
let worker_threads = env::var("TOKIO_WORKER_THREADS")
|
|
26
|
+
.ok()
|
|
27
|
+
.and_then(|v| v.parse::<usize>().ok())
|
|
28
|
+
.unwrap_or_else(|| {
|
|
29
|
+
// Alternatively clamp available_parallelism to realistic container quota
|
|
30
|
+
std::thread::available_parallelism()
|
|
31
|
+
.map(|p| p.get().clamp(1, 4)) // Never spawn unbounded threads on host
|
|
32
|
+
.unwrap_or(2)
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
tokio::runtime::Builder::new_multi_thread()
|
|
36
|
+
.worker_threads(worker_threads)
|
|
37
|
+
.max_blocking_threads(16) // Prevent unbounded blocking pool
|
|
38
|
+
.enable_all()
|
|
39
|
+
.build()
|
|
40
|
+
.expect("Failed to initialize Tokio runtime")
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
fn main() {
|
|
44
|
+
let rt = build_optimized_runtime();
|
|
45
|
+
rt.block_on(async_main());
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async fn async_main() {
|
|
49
|
+
// Application logic here
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
In your Kubernetes Deployment YAML, inject the thread count via Downward API:
|
|
54
|
+
```yaml
|
|
55
|
+
spec:
|
|
56
|
+
containers:
|
|
57
|
+
- name: my-service
|
|
58
|
+
resources:
|
|
59
|
+
requests:
|
|
60
|
+
cpu: "500m"
|
|
61
|
+
memory: "64Mi"
|
|
62
|
+
limits:
|
|
63
|
+
cpu: "1"
|
|
64
|
+
memory: "128Mi"
|
|
65
|
+
env:
|
|
66
|
+
- name: TOKIO_WORKER_THREADS
|
|
67
|
+
value: "2"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 2. Preventing `OOMKilled` (Exit Code 137)
|
|
73
|
+
|
|
74
|
+
### Cgroups Memory Limit vs RSS
|
|
75
|
+
When a container exceeds `resources.limits.memory`, the Linux kernel cgroups OOM-killer immediately dispatches `SIGKILL (Exit Code 137)`. Unlike garbage-collected runtimes, Rust does not perform GC sweeps under memory pressure.
|
|
76
|
+
|
|
77
|
+
### Best Practice: Guaranteed QoS & Threshold Trimming
|
|
78
|
+
1. **Match Requests and Limits (Guaranteed QoS)**: In memory-critical services, set `requests.memory == limits.memory`. This prevents the K8s node from overcommitting memory and evicting your pod when other noisy neighbor pods spike.
|
|
79
|
+
2. **Internal High-Watermark Trim**: If running with `glibc`, trigger `libc::malloc_trim(0)` when memory reaches 80% of container limits. If running with `tikv-jemallocator`, ensure `dirty_decay_ms:1000,muzzy_decay_ms:1000` is active.
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
resources:
|
|
83
|
+
requests:
|
|
84
|
+
cpu: "1"
|
|
85
|
+
memory: "128Mi"
|
|
86
|
+
limits:
|
|
87
|
+
cpu: "1"
|
|
88
|
+
memory: "128Mi" # Guaranteed QoS: lowest eviction priority
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## 3. Zero-Downtime Deployment & Graceful SIGTERM Handling
|
|
94
|
+
|
|
95
|
+
### The Ingress 502 Race Condition
|
|
96
|
+
During rolling updates (`kubectl rollout restart`):
|
|
97
|
+
1. K8s removes the Pod IP from the Service Endpoints.
|
|
98
|
+
2. Simultaneously, K8s sends `SIGTERM` to the container process.
|
|
99
|
+
3. Kube-proxy / Ingress controllers take **1 to 3 seconds** to propagate the route removal across all nodes.
|
|
100
|
+
4. If your Rust service exits immediately upon receiving `SIGTERM`, clients whose requests were in-flight or routed during that 2-second window receive `502 Bad Gateway` or `Connection Reset`.
|
|
101
|
+
|
|
102
|
+
### The Solution: Pre-Stop Sleep & Dual Signal Draining
|
|
103
|
+
In Kubernetes, configure a `preStop` hook to delay `SIGTERM` until kube-proxy has deregistered the pod, and handle graceful shutdown in Rust:
|
|
104
|
+
|
|
105
|
+
```yaml
|
|
106
|
+
lifecycle:
|
|
107
|
+
preStop:
|
|
108
|
+
exec:
|
|
109
|
+
command: ["/bin/sh", "-c", "sleep 3"]
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
In Rust (`Axum` shutdown signal):
|
|
113
|
+
```rust
|
|
114
|
+
use tokio::signal::unix::{signal, SignalKind};
|
|
115
|
+
|
|
116
|
+
pub async fn shutdown_signal() {
|
|
117
|
+
let ctrl_c = async {
|
|
118
|
+
tokio::signal::ctrl_c()
|
|
119
|
+
.await
|
|
120
|
+
.expect("Failed to listen for Ctrl+C");
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
#[cfg(unix)]
|
|
124
|
+
let terminate = async {
|
|
125
|
+
let mut sigterm = signal(SignalKind::terminate())
|
|
126
|
+
.expect("Failed to listen for SIGTERM");
|
|
127
|
+
sigterm.recv().await;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
#[cfg(not(unix))]
|
|
131
|
+
let terminate = std::future::pending::<()>();
|
|
132
|
+
|
|
133
|
+
tokio::select! {
|
|
134
|
+
_ = ctrl_c => {},
|
|
135
|
+
_ = terminate => {},
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
tracing::info!("Received termination signal. Draining in-flight requests...");
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 4. Probe Architecture (Liveness vs Readiness vs Startup)
|
|
145
|
+
|
|
146
|
+
Never bind expensive downstream checks (e.g. database ping, Redis cluster scan) to your **Liveness Probe**. If PostgreSQL experiences a temporary 5-second query spike, K8s will consider all Rust pods dead, kill them simultaneously, and trigger a catastrophic cluster-wide crash loop.
|
|
147
|
+
|
|
148
|
+
### Probe Separation of Concerns
|
|
149
|
+
|
|
150
|
+
| Probe Type | Purpose | Frequency | Safe Implementation |
|
|
151
|
+
| :--- | :--- | :--- | :--- |
|
|
152
|
+
| **Startup** | Allows cold start / migrations | 1s | Check schema migration or state init |
|
|
153
|
+
| **Liveness** | Checks if process / reactor is alive | 10s | Lightweight HTTP 200 OK (no external DB calls) |
|
|
154
|
+
| **Readiness** | Checks if pod can accept incoming traffic | 5s | Check DB pool available connections & Redis ping |
|
|
155
|
+
|
|
156
|
+
```rust
|
|
157
|
+
use axum::{routing::get, Router, http::StatusCode, extract::State};
|
|
158
|
+
use std::sync::Arc;
|
|
159
|
+
|
|
160
|
+
pub fn probe_routes() -> Router<Arc<AppState>> {
|
|
161
|
+
Router::new()
|
|
162
|
+
// Liveness: Zero allocation, purely tests if Tokio event loop responds
|
|
163
|
+
.route("/healthz/live", get(|| async { StatusCode::OK }))
|
|
164
|
+
// Readiness: Verifies database pool has available connections
|
|
165
|
+
.route("/healthz/ready", get(readiness_handler))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async fn readiness_handler(State(state): State<Arc<AppState>>) -> StatusCode {
|
|
169
|
+
// Fast check: verify at least 1 connection can be acquired within 500ms
|
|
170
|
+
match tokio::time::timeout(
|
|
171
|
+
std::time::Duration::from_millis(500),
|
|
172
|
+
state.db_pool.acquire(),
|
|
173
|
+
).await {
|
|
174
|
+
Ok(Ok(_conn)) => StatusCode::OK,
|
|
175
|
+
_ => StatusCode::SERVICE_UNAVAILABLE, // Temporarily stops traffic routing without killing pod
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## 5. Security & Read-Only Root Filesystem
|
|
183
|
+
|
|
184
|
+
Rust compiled binaries do not require root privileges, package managers, or writable filesystems at runtime:
|
|
185
|
+
|
|
186
|
+
```yaml
|
|
187
|
+
securityContext:
|
|
188
|
+
runAsNonRoot: true
|
|
189
|
+
runAsUser: 10001
|
|
190
|
+
runAsGroup: 10001
|
|
191
|
+
readOnlyRootFilesystem: true
|
|
192
|
+
allowPrivilegeEscalation: false
|
|
193
|
+
capabilities:
|
|
194
|
+
drop:
|
|
195
|
+
- ALL
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
---
|
|
199
|
+
|
|
200
|
+
## 6. Production Checklist
|
|
201
|
+
|
|
202
|
+
- [ ] Tokio worker threads explicitly bounded (`TOKIO_WORKER_THREADS`) to match container CPU limits.
|
|
203
|
+
- [ ] Memory `requests` equal `limits` (Guaranteed QoS) to avoid noisy-neighbor eviction.
|
|
204
|
+
- [ ] Ingress 502 race avoided via `preStop: sleep 3` or delayed signal drain.
|
|
205
|
+
- [ ] Liveness probe isolated from database/cache dependencies.
|
|
206
|
+
- [ ] Readiness probe fails gracefully (`503 Service Unavailable`) without triggering pod restarts.
|
|
207
|
+
- [ ] Binary runs as non-root with `readOnlyRootFilesystem: true`.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Linux Memory Allocator Tuning & Low-Level Libc ABI Hardening
|
|
2
|
+
1. How to tame glibc memory fragmentation (`MALLOC_ARENA_MAX=2` and `malloc_trim`).
|
|
3
|
+
2. How to avoid the **`libc.so` / GLIBC version mismatch** disaster in Docker multi-stage builds.
|
|
4
|
+
3. Why `malloc_trim` fails on Alpine (musl vs glibc target environments).
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. The Low-Level Docker `libc.so` Trap
|
|
9
|
+
|
|
10
|
+
When a Rust binary links to C libraries (such as `libc`, `libssl`, `libcrypto`), the compiled binary dynamically references specific symbol versions from `/lib/x86_64-linux-gnu/libc.so.6`.
|
|
11
|
+
|
|
12
|
+
### Why Builds Break:
|
|
13
|
+
1. **GLIBC Version Mismatch**:
|
|
14
|
+
If your `builder` image uses a newer Debian/Ubuntu release than your `runtime` image (for example, building on Debian Trixie with `GLIBC_2.38` and running on Debian Bookworm with `GLIBC_2.36`), the container crashes on start:
|
|
15
|
+
```text
|
|
16
|
+
/app/binary: /lib/x86_64-linux-gnu/libc.so.6: version 'GLIBC_2.38' not found
|
|
17
|
+
```
|
|
18
|
+
2. **The Alpine / Musl Trap (`malloc_trim` is GNU-only)**:
|
|
19
|
+
`libc::malloc_trim(0)` is a **GNU glibc-specific extension**. It does NOT exist in `musl` libc on Alpine. If you attempt to run on Alpine or compile with `musl`, linking will fail or crash.
|
|
20
|
+
3. **Missing CA Certificates & SSL Dynamic Libraries**:
|
|
21
|
+
Without `ca-certificates` and the matching runtime OpenSSL package (e.g. `libssl3` on Debian Bookworm), TLS requests via `reqwest` fail immediately with certificate verification errors or missing `libssl.so.3`.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 2. Hardened Production Dockerfile (Bulletproof Glibc ABI)
|
|
26
|
+
|
|
27
|
+
To guarantee 100% binary-ABI compatibility and zero `libc.so` errors:
|
|
28
|
+
- Pin the **exact same Debian codename** for both Builder and Runtime (e.g. `bookworm` and `bookworm-slim`).
|
|
29
|
+
- Install `ca-certificates` and `libssl3` in the runtime layer.
|
|
30
|
+
- Set `MALLOC_ARENA_MAX=2` directly in the runtime layer.
|
|
31
|
+
|
|
32
|
+
```dockerfile
|
|
33
|
+
# ========================================================
|
|
34
|
+
# STAGE 1: Builder (Exact Debian Bookworm glibc 2.36)
|
|
35
|
+
# ========================================================
|
|
36
|
+
FROM rust:1.96-slim-bookworm AS builder
|
|
37
|
+
|
|
38
|
+
# Install build dependencies for C-extensions & OpenSSL
|
|
39
|
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
40
|
+
pkg-config \
|
|
41
|
+
libssl-dev \
|
|
42
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
43
|
+
|
|
44
|
+
WORKDIR /usr/src/app
|
|
45
|
+
COPY . .
|
|
46
|
+
|
|
47
|
+
# Build stripped release binary
|
|
48
|
+
RUN cargo build --release
|
|
49
|
+
|
|
50
|
+
# ========================================================
|
|
51
|
+
# STAGE 2: Runtime (Identical Debian Bookworm glibc 2.36)
|
|
52
|
+
# ========================================================
|
|
53
|
+
FROM debian:bookworm-slim
|
|
54
|
+
|
|
55
|
+
# Install runtime dependencies: matching libssl and root CA certs
|
|
56
|
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
57
|
+
ca-certificates \
|
|
58
|
+
libssl3 \
|
|
59
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
60
|
+
|
|
61
|
+
WORKDIR /app
|
|
62
|
+
COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
|
|
63
|
+
|
|
64
|
+
# CRITICAL MEMORY & RUNTIME TUNING:
|
|
65
|
+
# 1. Restricts glibc multi-thread memory arenas (stops multi-thread RSS fragmentation)
|
|
66
|
+
ENV MALLOC_ARENA_MAX=2
|
|
67
|
+
ENV PORT=3000
|
|
68
|
+
|
|
69
|
+
EXPOSE 3000
|
|
70
|
+
|
|
71
|
+
# Run binary
|
|
72
|
+
CMD ["/app/app_binary"]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## 3. Safe Rust Code Guard for `malloc_trim`
|
|
78
|
+
|
|
79
|
+
Because `malloc_trim` is GNU glibc specific, protect it in your Rust source code so that it only compiles when targeting GNU Linux. This ensures your code doesn't break if someone builds on macOS, Windows, or an Alpine musl target:
|
|
80
|
+
|
|
81
|
+
### `Cargo.toml`
|
|
82
|
+
```toml
|
|
83
|
+
[target.'cfg(target_os = "linux")'.dependencies]
|
|
84
|
+
libc = "0.2"
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### `src/util.rs`
|
|
88
|
+
```rust
|
|
89
|
+
/// Release unused glibc allocator heap pages back to the Linux kernel.
|
|
90
|
+
/// Guarded with `target_env = "gnu"` so it compiles safely and won't panic on musl/macOS/Windows.
|
|
91
|
+
#[inline]
|
|
92
|
+
pub fn trim_memory() {
|
|
93
|
+
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
94
|
+
unsafe {
|
|
95
|
+
libc::malloc_trim(0);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## 4. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
|
|
103
|
+
|
|
104
|
+
Both production reference projects strictly target **`x86_64-unknown-linux-gnu`** (Debian Bookworm) rather than Alpine/musl:
|
|
105
|
+
|
|
106
|
+
1. **Musl Concurrency Performance Penalty**:
|
|
107
|
+
- The default allocator in `musl` (`mallocng`) is optimized for minimal binary footprint, not high-concurrency throughput.
|
|
108
|
+
- Under heavy Tokio multi-threaded traffic, musl suffers severe lock contention during simultaneous allocations/deallocations, often degrading throughput by 30%–50% compared to glibc.
|
|
109
|
+
- Musl does **not** provide `malloc_trim`. Once memory is mapped, there is no low-level API to force unmapped page return.
|
|
110
|
+
|
|
111
|
+
2. **The Glibc Arena Tradeoff (And How It's Solved)**:
|
|
112
|
+
- Glibc provides raw multi-threaded throughput, but introduces aggressive arena creation (`8 * CPU_CORES`), causing RSS phantom bloat.
|
|
113
|
+
- This skill applies the two-part containment recipe:
|
|
114
|
+
- `ENV MALLOC_ARENA_MAX=2` to limit arena fragmentation.
|
|
115
|
+
- `libc::malloc_trim(0)` to actively return idle pages to the Linux kernel.
|
|
116
|
+
|
|
117
|
+
3. **Strict Docker Base Image Pairing (Preventing `libc.so` Crashes)**:
|
|
118
|
+
- Dynamic linking requires that the runner image glibc version is identical to the builder image.
|
|
119
|
+
- NEVER mismatch codenames (e.g., building on Trixie/Sid and running on Bookworm).
|
|
120
|
+
- Always pair identical stages:
|
|
121
|
+
```dockerfile
|
|
122
|
+
FROM rust:1.96-slim-bookworm AS builder
|
|
123
|
+
...
|
|
124
|
+
FROM debian:bookworm-slim
|
|
125
|
+
```
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Message Queue Consumer Backpressure and Stream Ingestion
|
|
2
|
+
|
|
3
|
+
In event-driven architectures (Kafka, RabbitMQ, Redis Streams, AWS SQS), consumer workers frequently pull messages faster than the processing pipeline (database persistence, external APIs) can process them. Without hard-bounded prefetch limits and backpressure channels, message buffers grow unboundedly until the Linux kernel terminates the container via OOM.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The Consumer Prefetch OOM Trap
|
|
8
|
+
|
|
9
|
+
By default, message brokers try to maximize throughput by streaming hundreds or thousands of unacknowledged messages into the consumer application's memory buffers:
|
|
10
|
+
|
|
11
|
+
- **RabbitMQ**: Without `basic_qos(prefetch_count)`, RabbitMQ delivers all queue messages into client RAM.
|
|
12
|
+
- **Kafka**: Without tuning `queued.max.messages.kbytes` or `fetch.max.bytes`, `librdkafka` buffers tens of thousands of messages in memory.
|
|
13
|
+
- **Tokio Worker Pool**: Spawning `tokio::spawn` per incoming message creates an unbounded task queue.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## 2. Decoupled Pipeline with Bounded Channels
|
|
18
|
+
|
|
19
|
+
Decouple the message ingestion loop from the worker execution pool using a strictly bounded `tokio::sync::mpsc::channel`. When workers fall behind, the channel fills up and the ingestion loop naturally pauses at `.send().await`, preventing memory inflation:
|
|
20
|
+
|
|
21
|
+
```rust
|
|
22
|
+
use tokio::sync::mpsc;
|
|
23
|
+
use std::sync::Arc;
|
|
24
|
+
|
|
25
|
+
pub struct QueueMessage {
|
|
26
|
+
pub id: u64,
|
|
27
|
+
pub payload: bytes::Bytes,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
pub async fn run_bounded_consumer_pipeline<F, Fut>(
|
|
31
|
+
concurrency: usize,
|
|
32
|
+
process_fn: F,
|
|
33
|
+
) where
|
|
34
|
+
F: Fn(QueueMessage) -> Fut + Send + Sync + 'static,
|
|
35
|
+
Fut: std::future::Future<Output = ()> + Send + 'static,
|
|
36
|
+
{
|
|
37
|
+
// Bound the internal channel to 2x worker concurrency
|
|
38
|
+
let (tx, mut rx) = mpsc::channel::<QueueMessage>(concurrency * 2);
|
|
39
|
+
let process_fn = Arc::new(process_fn);
|
|
40
|
+
|
|
41
|
+
// Spawn fixed pool of async workers
|
|
42
|
+
for _ in 0..concurrency {
|
|
43
|
+
let mut rx = rx.clone(); // Or single worker draining rx
|
|
44
|
+
let process_fn = Arc::clone(&process_fn);
|
|
45
|
+
|
|
46
|
+
tokio::spawn(async move {
|
|
47
|
+
while let Some(msg) = rx.recv().await {
|
|
48
|
+
process_fn(msg).await;
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Ingestion loop: pauses automatically when channel is saturated
|
|
54
|
+
loop {
|
|
55
|
+
let raw_msg = fetch_next_broker_message().await;
|
|
56
|
+
|
|
57
|
+
// BACKPRESSURE APPLIED HERE:
|
|
58
|
+
// If all workers are busy and channel capacity is reached,
|
|
59
|
+
// this .send().await suspends execution and halts broker pulling.
|
|
60
|
+
if tx.send(raw_msg).await.is_err() {
|
|
61
|
+
break; // Pipeline shut down
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async fn fetch_next_broker_message() -> QueueMessage {
|
|
67
|
+
// Fetches from Kafka / RabbitMQ / SQS
|
|
68
|
+
QueueMessage { id: 1, payload: bytes::Bytes::from_static(b"data") }
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 3. RabbitMQ Prefetch Tuning (`lapin`)
|
|
75
|
+
|
|
76
|
+
In RabbitMQ AMQP consumers using `lapin`, always set `basic_qos` before consuming:
|
|
77
|
+
|
|
78
|
+
```rust
|
|
79
|
+
use lapin::{options::BasicQosOptions, Channel};
|
|
80
|
+
|
|
81
|
+
pub async fn configure_rabbitmq_channel(channel: &Channel, worker_concurrency: u16) -> Result<(), lapin::Error> {
|
|
82
|
+
// Only prefetch enough messages to keep workers busy
|
|
83
|
+
channel.basic_qos(
|
|
84
|
+
worker_concurrency * 2, // prefetch_count
|
|
85
|
+
BasicQosOptions::default(),
|
|
86
|
+
).await?;
|
|
87
|
+
|
|
88
|
+
Ok(())
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## 4. Kafka (`rdkafka`) Memory Containment
|
|
95
|
+
|
|
96
|
+
Configure `librdkafka` client properties to bound internal queue buffers:
|
|
97
|
+
|
|
98
|
+
```rust
|
|
99
|
+
use rdkafka::config::ClientConfig;
|
|
100
|
+
|
|
101
|
+
pub fn create_kafka_consumer_config() -> ClientConfig {
|
|
102
|
+
let mut config = ClientConfig::new();
|
|
103
|
+
config
|
|
104
|
+
.set("bootstrap.servers", "localhost:9092")
|
|
105
|
+
.set("group.id", "my-consumer-group")
|
|
106
|
+
.set("enable.auto.commit", "false")
|
|
107
|
+
// Limit internal queue buffer size to 16MB (default can be 1GB+)
|
|
108
|
+
.set("queued.max.messages.kbytes", "16384")
|
|
109
|
+
// Limit max fetch size per partition to 1MB
|
|
110
|
+
.set("fetch.message.max.bytes", "1048576")
|
|
111
|
+
.set("fetch.max.bytes", "10485760"); // Max 10MB per fetch request
|
|
112
|
+
|
|
113
|
+
config
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## 5. Production Checklist
|
|
120
|
+
|
|
121
|
+
- [ ] Bounded internal Tokio MPSC channels between consumer and worker pool.
|
|
122
|
+
- [ ] Set `basic_qos` prefetch limit on RabbitMQ channels.
|
|
123
|
+
- [ ] Configured `queued.max.messages.kbytes` on Kafka consumers to prevent GBs of buffered records.
|
|
124
|
+
- [ ] Offloaded heavy CPU decoding/parsing to `rayon` or `spawn_blocking` to avoid stalling the message ACK loop.
|
|
125
|
+
- [ ] Ensured offset commits only happen after processing has completed, preventing silent message loss during task drainage.
|