@sinkaroid/rust-shapeshift 0.0.0-stage → 1.0.3

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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/bin/rust-shapeshift.js +29 -0
  4. package/package.json +45 -4
  5. package/skills/rust-shapeshift/SKILL.md +282 -0
  6. package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +122 -0
  7. package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +139 -0
  8. package/skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md +83 -0
  9. package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +158 -0
  10. package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +145 -0
  11. package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +105 -0
  12. package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +147 -0
  13. package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +122 -0
  14. package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +121 -0
  15. package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +126 -0
  16. package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +170 -0
  17. package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +158 -0
  18. package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +115 -0
  19. package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +157 -0
  20. package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +143 -0
  21. package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +192 -0
  22. package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +117 -0
  23. package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +255 -0
  24. package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +113 -0
  25. package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +135 -0
  26. package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +146 -0
  27. package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +145 -0
  28. package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +207 -0
  29. package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +125 -0
  30. package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +125 -0
  31. package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +169 -0
  32. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +253 -0
  33. package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +94 -0
  34. package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +140 -0
  35. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +251 -0
  36. package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +230 -0
  37. package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +130 -0
  38. package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +108 -0
  39. package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +156 -0
  40. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +134 -0
  41. package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +97 -0
  42. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +170 -0
  43. package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +149 -0
  44. package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +124 -0
  45. package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +254 -0
  46. package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +114 -0
  47. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +130 -0
  48. package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +99 -0
  49. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +159 -0
  50. package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +109 -0
  51. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +104 -0
  52. package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +156 -0
@@ -0,0 +1,143 @@
1
+ # Rust Framework & Stack Selection Matrix
2
+
3
+ ## The Problem: The "One-Size-Fits-All" Architectural Trap
4
+
5
+ A frequent failure mode in Rust backend engineering is choosing a web framework based on hype or generic benchmark leaderboards rather than physical workload constraints.
6
+
7
+ Reaching for Tokio and Axum for an ephemeral monitoring sidecar wastes 20MB–40MB of memory on unused thread pools. Conversely, hand-rolling HTTP/1.1 parsers with `std::net` for a complex SaaS application wastes months reinventing routing, OpenAPI schemas, and multipart streams.
8
+
9
+ This playbook provides an objective, production-tested **Selection Matrix** comparing **Zero-Dependency Manual (`std::net`)**, **Axum**, **Actix Web**, **Salvo**, **Poem**, **Rocket**, and **Loco**.
10
+
11
+ ---
12
+
13
+ ## 1. Comprehensive Framework Comparison Matrix
14
+
15
+ | Stack / Framework | Idle RSS (Baseline) | Ecosystem & Runtime | Primary Architectural Strength | Weakness / Trade-off | Best Production Use Case |
16
+ | :--- | :--- | :--- | :--- | :--- | :--- |
17
+ | **Manual (Zero-Deps)** | **<1 MB** (~50KB) | Pure `std::net`, blocking I/O, static `musl` | Indestructible stability, 0 dependencies, instant builds (<2s). | No built-in routing, HTTP/2, or middleware. | Container sidecars, low-QPS daemons, CLI tools, embedded monitors. |
18
+ | **Axum** (v0.8+) | **15 MB – 35 MB** | Tokio multi-thread, Tower, Hyper | Official Tokio ecosystem standard, modular Tower middleware, type-safe extractors. | Requires Tokio overhead; Tower compiler errors can be complex. | Cloud microservices, REST/GraphQL gateways, WebSocket clusters. |
19
+ | **Actix Web** (v4+) | **20 MB – 45 MB** | Custom `actix-rt` multi-arbiter over Tokio | Top-tier raw throughput (TechEmpower), mature built-in HTTP primitives. | Heavy macro and unsafe usage; clunky Tower compatibility. | High-throughput public APIs, high-RPS batch ingestion engines. |
20
+ | **Salvo** | **20 MB – 40 MB** | Tokio, Hyper | Built-in OpenAPI (`oapi`), unified handlers, ACME auto-TLS, Go/Gin ergonomics. | Smaller English community; frequent API breaking changes across minors. | Fast REST API delivery with automatic OpenAPI documentation. |
21
+ | **Poem** | **18 MB – 38 MB** | Tokio, Hyper (also targets WASM) | First-class OpenAPI (`poem-openapi`) & GraphQL, elegant functional design. | Single primary maintainer; smaller third-party plugin ecosystem. | Contract-first OpenAPI services, type-driven GraphQL microservices. |
22
+ | **Rocket** (v0.5+) | **25 MB – 50 MB** | Tokio (migrated), custom state | Unmatched developer experience (DX), intuitive request guards, clean syntax. | Heavy procedural macro overhead (slower builds); higher memory footprint. | Internal tools, admin dashboards, rapid prototypes where DX > raw throughput. |
23
+ | **Loco** (Rails of Rust) | **40 MB – 75 MB** | Tokio, Axum, SeaORM | True batteries-included full-stack: DB migrations, background workers, auth, mailers. | Large dependency tree, long compile times, bloated for minimal microservices. | Full-stack web applications, SaaS MVPs, teams migrating from Rails/Django/Laravel. |
24
+
25
+ ---
26
+
27
+ ## 2. In-Depth Framework Breakdown: Pros & Cons
28
+
29
+ ### 1. Manual Zero-Dependency (The Koburi Pattern)
30
+ ```rust
31
+ use std::net::TcpListener;
32
+ use std::io::{Read, Write};
33
+
34
+ fn main() -> std::io::Result<()> {
35
+ let listener = TcpListener::bind("127.0.0.1:9911")?;
36
+ for stream in listener.incoming() {
37
+ let mut stream = stream?;
38
+ let mut buf = [0u8; 1024];
39
+ let _ = stream.read(&mut buf)?;
40
+ stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")?;
41
+ }
42
+ Ok(())
43
+ }
44
+ ```
45
+ * **Pros**: Sub-megabyte memory (53 kB verified idle RSS under continuous scraping), zero external crate vulnerabilities, compile times under 3 seconds, trivial static linking (`musl`).
46
+ * **Cons**: You must manually implement HTTP parsing, path routing, keepalive headers, and TLS.
47
+ * **When to Choose**: When the service runs on tight edge hardware, container sidecars (e.g. Istio/Grafana scraping sidecars), or polling jobs where an async executor is pure waste.
48
+
49
+ ---
50
+
51
+ ### 2. Axum (The Modern Cloud Standard)
52
+ ```rust
53
+ use axum::{routing::get, Router};
54
+
55
+ #[tokio::main]
56
+ async fn main() {
57
+ let app = Router::new().route("/health", get(|| async { "OK" }));
58
+ let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
59
+ axum::serve(listener, app).await.unwrap();
60
+ }
61
+ ```
62
+ * **Pros**: Developed by the Tokio team. Seamlessly interoperates with `tower`, `tower-http` (CORS, Trace, Compression), and `hyper`. Extractor model (`Path`, `Query`, `Json`, `State`) provides compile-time guarantee of request data. Minimal procedural macros mean fast compile times.
63
+ * **Cons**: No out-of-the-box CLI, ORM, or auth generators; you must assemble your own stack.
64
+ * **When to Choose**: Production cloud microservices, high-density WebSockets, Kubernetes deployments, and teams building long-term enterprise systems.
65
+
66
+ ---
67
+
68
+ ### 3. Actix Web (The High-Throughput Heavyweight)
69
+ * **Pros**: Consistently dominates raw requests-per-second benchmarks. Multi-arbiter architecture assigns dedicated single-threaded workers per OS thread, maximizing thread cache locality.
70
+ * **Cons**: Historical API instability, heavier binary footprint, custom actor runtime layer that complicates integration with generic Tokio libraries.
71
+ * **When to Choose**: When your business metric is maximum raw HTTP throughput per server node and you don't need Tower middleware interoperability.
72
+
73
+ ---
74
+
75
+ ### 4. Salvo (The All-In-One API Framework)
76
+ ```rust
77
+ use salvo::prelude::*;
78
+
79
+ #[handler]
80
+ async fn hello() -> &'static str {
81
+ "Hello World"
82
+ }
83
+
84
+ #[tokio::main]
85
+ async fn main() {
86
+ let router = Router::new().get(hello);
87
+ let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
88
+ Server::new(acceptor).serve(router).await;
89
+ }
90
+ ```
91
+ * **Pros**: Ergonomic handler design. Native built-in OpenAPI documentation generator (`salvo-oapi`), automated Let's Encrypt / ACME TLS certification, and built-in rate limiting. Feels like Go's Gin or Fiber.
92
+ * **Cons**: Heavy macro usage increases compiler load. Smaller community compared to Axum.
93
+ * **When to Choose**: Teams wanting built-in Swagger UI and OpenAPI generation without hand-crafting schema annotations across dozens of crates.
94
+
95
+ ---
96
+
97
+ ### 5. Poem (The OpenAPI & GraphQL Specialist)
98
+ * **Pros**: Exceptionally clean functional design. `poem-openapi` is arguably the cleanest OpenAPI 3.0 implementation in Rust with complete compile-time schema validation. First-class integration with `async-graphql`.
99
+ * **Cons**: Smaller ecosystem, heavily maintained by one developer.
100
+ * **When to Choose**: When your application is strictly contract-first OpenAPI or GraphQL and schema validation accuracy is your top priority.
101
+
102
+ ---
103
+
104
+ ### 6. Rocket (The DX & Prototype Champion)
105
+ * **Pros**: Beautiful, readable code. Request guards validate cookies, headers, and permissions effortlessly. Friendly compiler error messages and intuitive configuration management.
106
+ * **Cons**: Heavy reliance on procedural macros slows build times significantly. Higher memory baseline and less flexible for low-level socket manipulations.
107
+ * **When to Choose**: Fast prototypes, internal company dashboards, hackathons, or developers transitioning from Flask/Express who want maximum ergonomics.
108
+
109
+ ---
110
+
111
+ ### 7. Loco (The Full-Stack Rails of Rust)
112
+ ```bash
113
+ # Loco CLI generates the entire project structure
114
+ loco new
115
+ cargo loco start
116
+ ```
117
+ * **Pros**: Convention-over-configuration. Comes bundled with SeaORM database migrations, JWT authentication, background task queues, mailer templates, and scaffolding generators.
118
+ * **Cons**: Highest idle memory footprint (40MB–75MB), longest compilation times, large dependency graph. Violates minimalist microservice principles.
119
+ * **When to Choose**: Solo developers or small startups building a full-stack SaaS web application where rapid feature delivery and database scaffolding outweigh raw memory minimization.
120
+
121
+ ---
122
+
123
+ ## 3. Decision Tree: How to Guide the User
124
+
125
+ When a user asks: *"Framework apa yang harus gue pakai untuk project Rust ini?"*, follow this decision tree:
126
+
127
+ ```text
128
+ Are you building a full-stack monolithic SaaS with DB, Auth, and background queues?
129
+ ├── YES ──► LOCO (Fastest time-to-market, Rails-like conventions)
130
+ └── NO
131
+ │
132
+ Is this a simple background daemon, container monitor, CLI, or scraping sidecar?
133
+ ├── YES ──► MANUAL ZERO-DEPS / KOBURI PATTERN (Pure std::net, <1MB RSS, instant builds)
134
+ └── NO
135
+ │
136
+ Do you require automatic OpenAPI / Swagger UI generated directly from code?
137
+ ├── YES ──► SALVO (All-in-one) or POEM-OPENAPI (Contract-first)
138
+ └── NO
139
+ │
140
+ Is raw maximum RPS throughput the single defining KPI?
141
+ ├── YES ──► ACTIX WEB (TechEmpower champion, multi-arbiter)
142
+ └── NO ──► AXUM 0.8 (Default recommendation: Rock-solid Tokio standard, Tower ecosystem)
143
+ ```
@@ -0,0 +1,192 @@
1
+ # GraphQL Memory & Query Containment: Production Async-GraphQL in Axum
2
+
3
+ In GraphQL APIs, memory efficiency cannot be guaranteed by standard HTTP body limits alone. A seemingly small 2KB GraphQL query can trigger exponential in-memory execution trees via nested relationships, circular fragments, and unbatched resolver calls (the N+1 query problem).
4
+
5
+ Without strict schema-level containment, a single recursive GraphQL query can allocate hundreds of thousands of intermediate async futures, blowing process RSS past gigabytes in milliseconds.
6
+
7
+ This playbook documents how to build a high-throughput, memory-contained GraphQL server using **`async-graphql`** and **`async-graphql-axum`**.
8
+
9
+ ---
10
+
11
+ ## 1. Schema-Level Depth & Complexity Containment
12
+
13
+ Never expose an unconstrained GraphQL schema to production traffic. `async-graphql` provides compile-time schema builders with strict mathematical bounds:
14
+
15
+ ```toml
16
+ # Cargo.toml
17
+ [dependencies]
18
+ async-graphql = { version = "7.0", features = ["chrono"] }
19
+ async-graphql-axum = "7.0"
20
+ ```
21
+
22
+ ### Schema Construction with Hard Limits:
23
+ ```rust
24
+ use async_graphql::{EmptyMutation, EmptySubscription, Schema};
25
+ use std::sync::Arc;
26
+
27
+ pub type AppSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
28
+
29
+ pub fn build_schema(state: Arc<AppState>) -> AppSchema {
30
+ let mut builder = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
31
+ // 🚀 INJECT SHARED STATE: Zero-cost pointer reference across all resolvers
32
+ .data(state)
33
+ // 🛑 PREVENT RECURSIVE AST EXHAUSTION: Maximum nested selection depth
34
+ .limit_depth(5)
35
+ // 🛑 PREVENT COMPUTATIONAL ATTACKS: Maximum computed complexity ceiling
36
+ .limit_complexity(100);
37
+
38
+ // Disable schema introspection in production to protect schema memory and security
39
+ #[cfg(not(debug_assertions))]
40
+ {
41
+ builder = builder.disable_introspection();
42
+ }
43
+
44
+ builder.finish()
45
+ }
46
+ ```
47
+
48
+ ### Depth vs Complexity Guard Mechanics:
49
+ - **`limit_depth(5)`**: Blocks malicious nested queries like `{ user { posts { author { posts { author { id } } } } } }`.
50
+ - **`limit_complexity(100)`**: Calculates field cost weights. If a query requests 50 items and each item expands 10 sub-fields ($50 \times 10 = 500$), the query is aborted at the parser level before resolving a single field.
51
+
52
+ ---
53
+
54
+ ## 2. Solving the N+1 Memory Trap with `DataLoader`
55
+
56
+ The classic GraphQL memory and latency disaster is the **N+1 Resolver Problem**:
57
+ - Querying a list of 50 videos and resolving their uploader profile independently triggers **51 separate network requests/queries**, allocating 50 concurrent futures and duplicate in-memory data structures.
58
+
59
+ ### The Batched Zero-Allocation Solution:
60
+ Use `async_graphql::dataloader::DataLoader` to coalesce individual field requests across the entire execution tree into a single vectorized batch query:
61
+
62
+ ```rust
63
+ use async_graphql::dataloader::{DataLoader, Loader};
64
+ use std::collections::HashMap;
65
+ use std::sync::Arc;
66
+
67
+ pub struct UploaderLoader {
68
+ state: Arc<AppState>,
69
+ }
70
+
71
+ impl Loader<CompactString> for UploaderLoader {
72
+ type Value = UploaderProfile;
73
+ type Error = Arc<AppError>;
74
+
75
+ async fn load(
76
+ &self,
77
+ keys: &[CompactString],
78
+ ) -> Result<HashMap<CompactString, Self::Value>, Self::Error> {
79
+ // 🚀 SINGLE VECTORIZED LOOKUP: Fetch all 50 keys in one single roundtrip
80
+ let mut results = HashMap::with_capacity(keys.len());
81
+ let profiles = self.state.fetch_profiles_batch(keys).await?;
82
+
83
+ for profile in profiles {
84
+ results.insert(profile.id.clone(), profile);
85
+ }
86
+
87
+ Ok(results)
88
+ }
89
+ }
90
+ ```
91
+
92
+ ### Registering DataLoader in Schema State:
93
+ ```rust
94
+ let loader = DataLoader::new(
95
+ UploaderLoader { state: state.clone() },
96
+ tokio::spawn, // Batch executor
97
+ ).max_batch_size(100);
98
+
99
+ let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
100
+ .data(loader)
101
+ .finish();
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 3. Resolvers with Zero-Copy State Access
107
+
108
+ Never clone entire application state or configurations inside field resolvers. Extract borrowed references directly from the GraphQL execution context (`&Context<'_>`):
109
+
110
+ ```rust
111
+ use async_graphql::{Context, Object, Result};
112
+ use std::sync::Arc;
113
+
114
+ pub struct QueryRoot;
115
+
116
+ #[Object]
117
+ impl QueryRoot {
118
+ async fn video<'ctx>(&self, ctx: &Context<'ctx>, id: String) -> Result<VideoType> {
119
+ // Borrow state from context (0 heap allocations)
120
+ let state = ctx.data::<Arc<AppState>>()?;
121
+
122
+ let video_data = state.get_video(&id).await
123
+ .map_err(|e| async_graphql::Error::new(e.to_string()))?;
124
+
125
+ Ok(VideoType::from(video_data))
126
+ }
127
+
128
+ async fn search<'ctx>(
129
+ &self,
130
+ ctx: &Context<'ctx>,
131
+ query: String,
132
+ limit: Option<usize>,
133
+ ) -> Result<Vec<VideoCardType>> {
134
+ let state = ctx.data::<Arc<AppState>>()?;
135
+
136
+ // Enforce hard ceiling on pagination limit
137
+ let bounded_limit = limit.unwrap_or(20).min(50);
138
+ let items = state.search_videos(&query, bounded_limit).await?;
139
+
140
+ Ok(items.into_iter().map(VideoCardType::from).collect())
141
+ }
142
+ }
143
+ ```
144
+
145
+ ---
146
+
147
+ ## 4. Production Axum 0.8 Router Integration
148
+
149
+ Expose both the POST execution route and an optional GraphiQL playground interface using `async-graphql-axum`:
150
+
151
+ ```rust
152
+ use async_graphql::http::GraphiQLSource;
153
+ use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
154
+ use axum::{
155
+ extract::State,
156
+ response::{Html, IntoResponse},
157
+ routing::{get, post},
158
+ Router,
159
+ };
160
+ use std::sync::Arc;
161
+
162
+ // GraphQL execution handler
163
+ pub async fn graphql_handler(
164
+ State(schema): State<AppSchema>,
165
+ req: GraphQLRequest,
166
+ ) -> GraphQLResponse {
167
+ schema.execute(req.into_inner()).await.into()
168
+ }
169
+
170
+ // GraphiQL development IDE (disabled in strict production environments)
171
+ pub async fn graphiql_ide() -> impl IntoResponse {
172
+ Html(GraphiQLSource::build().endpoint("/graphql").finish())
173
+ }
174
+
175
+ // Router assembly
176
+ pub fn configure_graphql_routes(schema: AppSchema) -> Router {
177
+ Router::new()
178
+ .route("/graphql", post(graphql_handler))
179
+ .route("/graphiql", get(graphiql_ide))
180
+ .with_state(schema)
181
+ }
182
+ ```
183
+
184
+ ---
185
+
186
+ ## 5. GraphQL Security & Memory Checklist
187
+
188
+ 1. Is `limit_depth` configured (recommended: 5–7 levels maximum)?
189
+ 2. Is `limit_complexity` applied to constrain expensive multiply-nested lists?
190
+ 3. Is schema introspection disabled in production via `.disable_introspection()`?
191
+ 4. Are recursive relational lookups batched via `DataLoader` to eliminate N+1 allocations?
192
+ 5. Are all query list limits (`limit: Option<usize>`) clamped to a strict maximum (e.g., `.min(50)`)?
@@ -0,0 +1,117 @@
1
+ # gRPC, Tonic, and HTTP/2 Memory Tuning
2
+
3
+ gRPC services implemented with Tonic run on top of HTTP/2 (`hyper`). Under high traffic bursts or large streaming transfers, default HTTP/2 flow-control window sizes and buffering mechanisms cause memory to balloon across open streams.
4
+
5
+ ---
6
+
7
+ ## 1. HTTP/2 Flow-Control Window Sizing
8
+
9
+ ### The Problem
10
+ HTTP/2 uses stream-level and connection-level flow control windows. The default window sizes can buffer megabytes of frames per active stream. At 10,000 concurrent RPC streams, unmetered window sizes can consume gigabytes of memory buffering frames before the server application has consumed them.
11
+
12
+ ### The Solution: Tuned Flow Control
13
+ Bound initial stream and connection windows on `Server::builder()`:
14
+
15
+ ```rust
16
+ use tonic::transport::Server;
17
+ use std::time::Duration;
18
+
19
+ pub async fn run_grpc_server(addr: std::net::SocketAddr) -> Result<(), Box<dyn std::error::Error>> {
20
+ Server::builder()
21
+ // Limit individual stream window to 64KB (prevents per-stream heap bloat)
22
+ .initial_stream_window_size(Some(64 * 1024))
23
+ // Limit connection-wide window to 512KB across all concurrent streams
24
+ .initial_connection_window_size(Some(512 * 1024))
25
+ // Limit maximum frame size to 16KB (HTTP/2 minimum default)
26
+ .max_frame_size(Some(16 * 1024))
27
+ // Limit concurrent streams per HTTP/2 connection
28
+ .max_concurrent_streams(Some(1024))
29
+ // HTTP/2 Keepalive to reclaim dead connections
30
+ .http2_keepalive_interval(Some(Duration::from_secs(30)))
31
+ .http2_keepalive_timeout(Some(Duration::from_secs(5)))
32
+ // Add services...
33
+ .serve(addr)
34
+ .await?;
35
+
36
+ Ok(())
37
+ }
38
+ ```
39
+
40
+ ---
41
+
42
+ ## 2. Zero-Copy Byte Streaming in gRPC
43
+
44
+ Avoid materializing intermediate `Vec<u8>` arrays during streaming RPCs. Use `prost::bytes::Bytes` which uses reference-counted slice slicing (`.slice()`) without copying underlying buffers:
45
+
46
+ ```rust
47
+ use tonic::{Request, Response, Status};
48
+ use prost::bytes::Bytes;
49
+ use tokio_stream::Stream;
50
+ use tokio_stream::wrappers::ReceiverStream;
51
+ use tokio::sync::mpsc;
52
+
53
+ pub struct StreamService;
54
+
55
+ #[tonic::async_trait]
56
+ impl my_proto::stream_service_server::StreamService for StreamService {
57
+ type StreamDataStream = ReceiverStream<Result<my_proto::DataChunk, Status>>;
58
+
59
+ async fn stream_data(
60
+ &self,
61
+ request: Request<my_proto::StreamRequest>,
62
+ ) -> Result<Response<Self::StreamDataStream>, Status> {
63
+ // Strictly bounded channel buffer (prevents producer from running away)
64
+ let (tx, rx) = mpsc::channel(32);
65
+
66
+ tokio::spawn(async move {
67
+ let chunk_data: Bytes = Bytes::from_static(b"OPTIMIZED_ZERO_COPY_PAYLOAD");
68
+
69
+ for _ in 0..1000 {
70
+ let msg = my_proto::DataChunk {
71
+ // Slices Bytes without memory copy or allocation
72
+ payload: chunk_data.slice(..),
73
+ };
74
+
75
+ // Propagate backpressure: await yields if client is slow reading
76
+ if tx.send(Ok(msg)).await.is_err() {
77
+ break; // Client disconnected or cancelled
78
+ }
79
+ }
80
+ });
81
+
82
+ Ok(Response::new(ReceiverStream::new(rx)))
83
+ }
84
+ }
85
+ ```
86
+
87
+ ---
88
+
89
+ ## 3. Tonic Client Channel Pooling & Bounded Buffers
90
+
91
+ Do not create a new `Channel` per outbound gRPC call. Use a shared, pooled channel with configured concurrency and window bounds:
92
+
93
+ ```rust
94
+ use tonic::transport::{Channel, Endpoint};
95
+ use std::time::Duration;
96
+
97
+ pub async fn create_optimized_channel(dst: &'static str) -> Result<Channel, tonic::transport::Error> {
98
+ Endpoint::from_static(dst)
99
+ .timeout(Duration::from_secs(5))
100
+ .connect_timeout(Duration::from_secs(3))
101
+ .initial_stream_window_size(Some(64 * 1024))
102
+ .initial_connection_window_size(Some(512 * 1024))
103
+ .tcp_nodelay(true)
104
+ .connect()
105
+ .await
106
+ }
107
+ ```
108
+
109
+ ---
110
+
111
+ ## 4. Production Checklist
112
+
113
+ - [ ] Enforced `initial_stream_window_size(64 * 1024)` on Tonic Server.
114
+ - [ ] Enforced `initial_connection_window_size(512 * 1024)` on Tonic Server.
115
+ - [ ] Bounded streaming MPSC channels to low numbers (e.g. 16–64) for backpressure propagation.
116
+ - [ ] Protobuf messages use `bytes::Bytes` rather than `Vec<u8>` for binary data payloads.
117
+ - [ ] Tonic client channels are created as shared singletons inside `Arc<AppState>`.