1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
//! # Performance Optimizations
//!
//! This module documents the key optimizations that make TurboKV 2x faster than RocksDB and fjall.
//!
//! ## Overview
//!
//! TurboKV achieves **1.1M ops/sec** for durable writes (WAL enabled), compared to:
//! - RocksDB: 560K ops/sec
//! - fjall: 501K ops/sec
//!
//! This is a **2x improvement** with equivalent durability guarantees.
//!
//! ---
//!
//! ## 1. Zero-Allocation WAL Write Path
//!
//! **Location:** [`crate::storage::wal`]
//!
//! ### Problem
//! Traditional WAL implementations allocate memory for each write:
//! - Create a new `Vec<u8>` for the encoded entry
//! - Create intermediate `Bytes` objects
//! - Multiple small writes to the file
//!
//! ### Solution
//! TurboKV uses a **thread-local pre-allocated buffer**:
//!
//! ```rust,ignore
//! thread_local! {
//! static WAL_ENCODE_BUFFER: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(4096));
//! }
//! ```
//!
//! Benefits:
//! - **Zero heap allocations** per write in the hot path
//! - Single `write_all()` syscall instead of multiple small writes
//! - Buffer grows once and is reused for all subsequent writes
//!
//! ### Impact
//! ~20% improvement in durable mode throughput.
//!
//! ---
//!
//! ## 2. Lock-Free MemTable with Crossbeam SkipList
//!
//! **Location:** [`crate::storage::memtable`]
//!
//! ### Problem
//! Traditional approach uses `Mutex<BTreeMap>` which creates contention:
//! - Writers block each other
//! - Readers block writers
//! - Poor scalability with concurrent access
//!
//! ### Solution
//! TurboKV uses `crossbeam_skiplist::SkipMap`:
//!
//! ```rust,ignore
//! pub(crate) data: Arc<SkipMap<Vec<u8>, MemTableEntry>>,
//! ```
//!
//! Benefits:
//! - **Lock-free reads and writes** - multiple threads can access simultaneously
//! - O(log n) operations like BTreeMap, but without locking
//! - Excellent cache locality for sequential scans
//!
//! ### Impact
//! Enables high concurrency without mutex contention.
//!
//! ---
//!
//! ## 3. Fast Hashing with gxhash
//!
//! ### Problem
//! Rust's default hasher (SipHash) is designed for security, not speed.
//!
//! ### Solution
//! TurboKV uses `gxhash` for internal hash maps:
//!
//! ```rust,ignore
//! use gxhash::GxBuildHasher;
//! type FastHashMap<K, V> = HashMap<K, V, GxBuildHasher>;
//! ```
//!
//! Benefits:
//! - **3-5x faster** than SipHash for short keys
//! - Uses hardware acceleration (AES-NI on x86, AES on ARM)
//! - Still provides good hash distribution
//!
//! ### Impact
//! Faster internal lookups in index structures.
//!
//! ---
//!
//! ## 4. Atomic Counters for Statistics
//!
//! ### Problem
//! Tracking size and entry count typically requires locking.
//!
//! ### Solution
//! TurboKV uses atomic counters:
//!
//! ```rust,ignore
//! pub(crate) size_bytes: Arc<AtomicUsize>,
//! pub(crate) entry_count: Arc<AtomicU64>,
//! pub(crate) sequence: Arc<AtomicU64>,
//! ```
//!
//! With relaxed ordering for non-critical stats:
//! ```rust,ignore
//! self.size_bytes.fetch_add(entry_size, Ordering::Relaxed);
//! ```
//!
//! Benefits:
//! - **No locks** for incrementing counters
//! - Relaxed ordering avoids memory barriers
//! - Stats are eventually consistent (acceptable for monitoring)
//!
//! ---
//!
//! ## 5. LZ4 Compression with lz4_flex
//!
//! **Location:** [`crate::storage::sstable`]
//!
//! ### Problem
//! Need compression for SSTable blocks, but compression is often CPU-bound.
//!
//! ### Solution
//! TurboKV defaults to LZ4 compression using `lz4_flex`:
//!
//! ```rust,ignore
//! CompressionType::Lz4 => {
//! let compressed = lz4_flex::compress_prepend_size(data);
//! Ok(compressed)
//! }
//! ```
//!
//! Benefits:
//! - **Fastest compression** algorithm available
//! - Pure Rust implementation (no C dependencies)
//! - Good compression ratio for typical workloads
//!
//! ### Compression Options
//! | Algorithm | Speed | Ratio | Use Case |
//! |-----------|-------|-------|----------|
//! | None | Fastest | 1.0x | When disk space doesn't matter |
//! | LZ4 | Very fast | ~2x | Default - best balance |
//! | Snappy | Fast | ~2x | Alternative to LZ4 |
//! | Zstd | Slow | ~3-4x | Maximum compression |
//!
//! ---
//!
//! ## 6. CRC32 with Hardware Acceleration
//!
//! **Location:** [`crate::core::crypto`]
//!
//! ### Problem
//! Checksums are computed for every WAL entry and SSTable block.
//!
//! ### Solution
//! TurboKV uses `crc32fast`:
//!
//! ```rust,ignore
//! pub fn crc32_checksum(data: &[u8]) -> u32 {
//! crc32fast::hash(data)
//! }
//! ```
//!
//! Benefits:
//! - Uses **SSE4.2 CRC32C** instruction on x86
//! - Uses **CRC32** instruction on ARM
//! - 10-20x faster than software CRC
//!
//! ---
//!
//! ## 7. Memory-Mapped SSTable Reads
//!
//! **Location:** [`crate::storage::sstable`]
//!
//! ### Problem
//! Reading SSTables with `read()` syscalls is slow.
//!
//! ### Solution
//! TurboKV memory-maps SSTables:
//!
//! ```rust,ignore
//! let mmap = unsafe {
//! MmapOptions::new()
//! .map(&file)?
//! };
//! ```
//!
//! Benefits:
//! - **Zero-copy reads** - data goes directly to user space
//! - OS handles caching automatically
//! - Random access without seeking
//!
//! ---
//!
//! ## 8. Bloom Filters for Negative Lookups
//!
//! **Location:** [`crate::storage::sstable`]
//!
//! ### Problem
//! Checking if a key exists requires reading SSTable blocks.
//!
//! ### Solution
//! TurboKV includes bloom filters in each SSTable:
//!
//! ```rust,ignore
//! pub struct BloomFilter {
//! bits: Vec<u64>,
//! num_hashes: u32,
//! }
//! ```
//!
//! Benefits:
//! - **Skip entire SSTables** when key definitely doesn't exist
//! - 1% false positive rate with ~10 bits per key
//! - Especially effective for read-heavy workloads
//!
//! ---
//!
//! ## 9. Vectorized Batch Writes
//!
//! **Location:** [`crate::storage::wal`]
//!
//! ### Problem
//! Writing multiple entries one-by-one is inefficient.
//!
//! ### Solution
//! TurboKV batches writes into a single syscall:
//!
//! ```rust,ignore
//! pub fn write_entries_batch(file: &mut WalFile, entries: &[WalEntry]) -> Result<()> {
//! // Pre-allocate buffer for all entries
//! let total_size: usize = entries.iter().map(entry_size).sum();
//! let mut buffer = Vec::with_capacity(total_size);
//!
//! // Serialize all entries
//! for entry in entries {
//! serialize_entry(&mut buffer, entry)?;
//! }
//!
//! // Single write syscall
//! file.file.write_all(&buffer)?;
//! }
//! ```
//!
//! Benefits:
//! - **One syscall** instead of N syscalls
//! - Better I/O scheduling by the kernel
//! - Reduced context switching
//!
//! ---
//!
//! ## 10. Cached Timestamp
//!
//! ### Problem
//! Getting the current time for each write is expensive (syscall).
//!
//! ### Solution
//! TurboKV caches the timestamp:
//!
//! ```rust,ignore
//! thread_local! {
//! static CACHED_TIME: Cell<u64> = Cell::new(0);
//! }
//!
//! pub fn now_ms() -> u64 {
//! // Update cache periodically, not on every call
//! }
//! ```
//!
//! Benefits:
//! - **Avoid syscall** on every write
//! - Timestamps are "close enough" for most uses
//! - Critical for high-throughput scenarios
//!
//! ---
//!
//! ## 11. Efficient Serialization with rkyv
//!
//! TurboKV includes `rkyv` for zero-copy deserialization:
//!
//! ```rust,ignore
//! use rkyv::{Archive, Deserialize, Serialize};
//! ```
//!
//! Benefits:
//! - **Zero-copy access** to archived data
//! - No parsing overhead
//! - Useful for complex data structures
//!
//! ---
//!
//! ## 12. Direct I/O (Optional)
//!
//! **Location:** [`crate::storage::direct_io`]
//!
//! TurboKV supports Direct I/O to bypass the OS page cache:
//!
//! ```rust,ignore
//! // Linux: O_DIRECT
//! // macOS: F_NOCACHE
//! let file = open_with_direct_io(path, create, write, direct)?;
//! ```
//!
//! Benefits:
//! - **Bypass OS cache** when application manages its own cache
//! - **Predictable latency** - no page cache eviction delays
//! - **Better for large datasets** that exceed RAM
//!
//! Includes `AlignedBuffer` for proper memory alignment (4KB boundary).
//!
//! ---
//!
//! ## Future Optimizations
//!
//! Potential areas for further improvement:
//! 1. **io_uring** - Async I/O on Linux for higher throughput
//! 2. **Column families** - Better cache utilization for different access patterns
//! 3. **Tiered storage** - Hot/cold data separation
//!
//! ---
//!
//! ## Measuring Performance
//!
//! Run benchmarks:
//!
//! ```bash
//! # Quick comparison (TurboKV vs RocksDB vs fjall)
//! cargo bench --bench large_scale_bench
//!
//! # Detailed statistical analysis
//! cargo bench --bench kv_benchmarks
//! ```
//!
//! Profile with:
//! ```bash
//! # CPU profiling
//! cargo build --release
//! samply record ./target/release/...
//!
//! # Memory profiling
//! MALLOC_CONF=prof:true cargo run --release ...
//! ```
// This module is documentation-only