Tiered Storage
Transparently extend a local Engine to an S3-compatible cold archive. Writes stay fast and local; reads fall through to remote only on a miss.
What is tiering
A single Engine stores data on local disk. Once segments are sealed and immutable, they can be uploaded to an object store — S3, MinIO, Cloudflare R2, GCS — and eventually pruned from local disk. Future reads that miss the local cache silently fetch the matching segment from remote, merge it, and return the result.
edgestore-tier implements this as TieredEngine: a thin wrapper that owns a local Engine and a Box<dyn RemoteStore>. No background threads. No daemon process. You call archive_segments when your policy says it's time.
Cargo dependencies
[dependencies]
edgestore-tier = "2.2.1"
edgestore-repl = { version = "2.2.1", features = ["s3"] } # for S3RemoteStore
Segment lifecycle
Write → memtable
put / delete land in the in-memory memtable. No S3 involved.
Flush → sealed segment on local disk
flush_to_segments() writes a segment-NNNNNNNN.dat file. The segment is now immutable; its BLAKE3 hash is its identity everywhere.
Archive → upload to remote
archive_segments(&metas) reads each .dat file and calls remote.upload_if_absent(hash, data). Already-uploaded segments are skipped (idempotent). The segment is registered in the local archived list.
Prune → reclaim local disk (optional)
Once archived, call prune_local_segment(segment_id) to delete the local .dat. The remote copy remains. Do this only after confirming the segment is in archived_segments().
Miss → fetch from remote
get() misses local, scans the archived list by key bounds, downloads the matching segment, imports it into local storage (LWW merge), and returns the value. Subsequent reads are local hits.
Setup
Builder methods chain off TieredEngine::new. All are optional.
use edgestore::{EdgestoreConfig, Engine};
use edgestore_repl::S3RemoteStore;
use edgestore_tier::TieredEngine;
let local = Engine::open(EdgestoreConfig::new("/var/db/hot"))?;
let remote = S3RemoteStore::new(
"my-bucket", // bucket name
Some("myapp/"), // optional key prefix
None, // None = standard AWS endpoint
)?;
let mut tiered = TieredEngine::new(local, Box::new(remote))
.with_segment_cache_bytes(32 * 1024 * 1024) // 32 MB ephemeral cache
.with_text_stripping(true) // strip BM25 after archive
.with_vector_stripping(true) // strip __vec__ after archive
.with_sidecars(true); // upload .idx/.xf/.meta
| Builder | Default | Effect |
|---|---|---|
| with_segment_cache_bytes(n) | 32 MB | LRU byte budget for ephemeral range/prefix reads. Set 0 to disable. |
| with_text_stripping(true) | false | After archive, remove __text__* records from local copy. |
| with_vector_stripping(true) | false | After archive, remove __vec__* records from local copy. |
| with_sidecars(true) | false | Upload .idx, .xf, .meta alongside each .dat. |
Monitor-and-archive pattern
EdgeStore is caller-driven. Your application controls when to archive and how many segments to keep hot. A common pattern: archive when segment count exceeds a threshold, keep the N most recent segments local.
loop {
// ... handle requests ...
let metas = tiered.local().list_segment_metas();
if metas.len() > 8 {
// archive the oldest; keep 4 most recent hot
let to_archive = &metas[..metas.len() - 4];
tiered.archive_segments(to_archive)?;
// optionally reclaim local disk
for m in to_archive {
tiered.prune_local_segment(m.segment_id)?;
}
}
}
// After restart: restore the archived list from your persistence layer
// (you must save archived_segments() somewhere — a JSON file, a DB row, etc.)
tiered.register_archived(load_archived_from_disk());
Persist the archived list. archived_segments() returns a Vec<ArchivedSegment> (each has hash, min_key, max_key). Serialize this after every archive_segments call and call register_archived on startup. Without it, remote segments will not be considered on reads after a restart.
Read-through behavior
get()
Tries local first. On miss, finds archived segments whose [min_key, max_key] bounds contain the encoded key, downloads and imports them (LWW merge), then retries locally. Once fetched, segments are cached in self.fetched — no re-download within a session.
range() and prefix()
Scans local, then builds an ephemeral ImmutableEngine from all archived segments whose key bounds overlap the query. Segment bytes are served from the LRU byte cache when available — no disk write, no permanent import. Local data wins for any key present in both sources.
Async fast-path (AsyncTieredEngine)
Call get_needs_archived_fetch(ns, key) under a read lock before escalating to a write lock. When it returns false, the local-only result is the complete answer — no writer needed.
Selective pre-fetch
// Pre-fetch only segments that overlap a known time range
tiered.fetch_archived_overlapping(b"logs", b"2026-01-01", b"2026-01-31")?;
// Download bytes without importing (ephemeral, for your own ImmutableEngine)
let bytes = tiered.download_segment(&hash)?;
// Warm everything (disaster recovery / full replay)
tiered.fetch_all_archived()?;
Index stripping
After archiving a segment to remote, the full-text BM25 index and HNSW vector index embedded in the local copy become redundant — the remote copy retains them. Stripping removes those records from local disk after each successful upload.
Text stripping
.with_text_stripping(true)
Removes __text__* namespace records after archive. Trade-off: rebuild_text_indices cannot reconstruct entries for stripped segments — only use after the merged __index__ sidecar has been flushed.
Vector stripping
.with_vector_stripping(true)
Removes __vec__* namespace records after archive. HNSW queries on stripped segments fall through to remote. Combine with text stripping for maximum reclaim.
Sidecars
With with_sidecars(true), archive_segments uploads three auxiliary files alongside each .dat segment:
| File | Contents |
|---|---|
| {hash}.idx | Key index for direct offset lookup without full scan |
| {hash}.xf | XOR filter for fast key-not-present probes |
| {hash}.meta | Segment metadata (key bounds, record count, hash) |
Sidecar upload errors are logged and skipped — the .dat alone is sufficient for correctness. Sidecars enable ImmutableEngine to reconstruct its in-memory index faster on replica nodes.
Retry behavior
Both upload_with_retry (called from archive_segments) and the download path inside get() use the same retry_transient policy:
| Constant | Value | Meaning |
|---|---|---|
| MAX_RETRIES | 3 | Maximum attempts after the first failure |
| BASE_DELAY_MS | 10 ms | Exponential backoff base: delay = 10 × 2^attempt ms |
| Transient triggers | "throttled" "timeout" "503" |
Non-transient errors (404, 403, hash mismatch) fail immediately without retry |
Delays: 10 ms, 20 ms, 40 ms. Total worst-case wait before failure: 70 ms. Uploads use upload_if_absent (idempotent) so retrying a partially-completed upload never creates a duplicate.
Local testing with MinIO
MinIO is a single-container S3-compatible object store. It supports path-style addressing and requires no AWS account. The project ships a docker-compose.yml and a Makefile target.
Quick start
# Start MinIO and create the test bucket
make s3-up
# Run all S3 integration tests
make s3-test
# Stop and remove the container
make s3-down
Manual run
# Start container
docker run -d --name edgestore-minio \
-p 9000:9000 -p 9001:9001 \
-e MINIO_ROOT_USER=minioadmin \
-e MINIO_ROOT_PASSWORD=minioadmin \
minio/minio:latest server /data --console-address ":9001"
# Create bucket
AWS_ACCESS_KEY_ID=minioadmin \
AWS_SECRET_ACCESS_KEY=minioadmin \
aws s3 mb s3://edgestore-test --endpoint-url http://localhost:9000
# Run edgestore-tier integration tests
EDGESTORE_S3_ENDPOINT_URL=http://localhost:9000 \
EDGESTORE_S3_BUCKET=edgestore-test \
AWS_ACCESS_KEY_ID=minioadmin \
AWS_SECRET_ACCESS_KEY=minioadmin \
AWS_DEFAULT_REGION=us-east-1 \
cargo test --package edgestore-tier --test integration_s3 -- --nocapture
Environment variables
EDGESTORE_S3_ENDPOINT_URLOverride endpoint (required for MinIO/local)EDGESTORE_S3_BUCKETBucket name (default: edgestore-test)AWS_ACCESS_KEY_IDAccess keyAWS_SECRET_ACCESS_KEYSecret keyAWS_DEFAULT_REGIONRegion (MinIO: us-east-1)MinIO console
After make s3-up, open http://localhost:9001 in a browser. Login: minioadmin / minioadmin. Browse buckets, inspect uploaded segments, and verify key layout.
Skip behavior
S3 tests skip gracefully when EDGESTORE_S3_ENDPOINT_URL is not set — they print skip: EDGESTORE_S3_ENDPOINT_URL not set and return. The full unit test suite (cargo test --workspace) always passes without a running container.
Production: AWS S3
Credentials
Credentials are resolved by the standard aws-config chain in order: environment variables → ~/.aws/credentials → IAM instance role (EC2/ECS) → IMDS. Pass None as endpoint_url to use the standard AWS endpoint.
// Production: standard AWS endpoint, credentials from env or IAM role
let remote = S3RemoteStore::new(
"my-prod-bucket",
Some("edgestore/"), // key prefix — recommended in shared buckets
None, // None = standard AWS endpoint
)?;
IAM policy (minimum)
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-prod-bucket",
"arn:aws:s3:::my-prod-bucket/edgestore/*"
]
}
Key layout in the bucket
{prefix}segments/{blake3_hex_64}.dat # segment data
{prefix}segments/{blake3_hex_64}.idx # key index sidecar
{prefix}segments/{blake3_hex_64}.xf # xor filter sidecar
{prefix}segments/{blake3_hex_64}.meta # segment metadata sidecar
S3 bucket settings
- Versioning: not required — segments are content-addressed and immutable.
- Lifecycle policy: recommended for pruned segments. Target prefix
{prefix}segments/with a 30-day expiry after your retention window. - Storage class: S3 Standard for active workloads; S3-IA or Glacier for deep cold archive. Glacier retrieval latency is incompatible with synchronous read-through — use it only with pre-fetch patterns.
- Encryption: SSE-S3 or SSE-KMS both work transparently.
- Path-style addressing: forced on when an endpoint URL is provided (MinIO / local testing). Not needed for standard AWS.
S3-compatible backends
Any service that speaks the S3 API works. Pass its endpoint URL as the third argument to S3RemoteStore::new. Path-style addressing is enabled automatically when an endpoint URL is present.
AWS S3
The canonical target. Pass None for endpoint; credentials via env or IAM role.
S3RemoteStore::new(
"bucket", prefix,
None // standard AWS
)Cloudflare R2
S3-compatible, no egress fees. Endpoint: https://{account}.r2.cloudflarestorage.com
S3RemoteStore::new(
"bucket", prefix,
Some("https://…r2…")
)Google Cloud Storage
S3 interop endpoint. Requires HMAC credentials, not service-account JSON.
S3RemoteStore::new(
"bucket", prefix,
Some("https://storage.googleapis.com")
)MinIO (local dev)
Single Docker container. make s3-up starts it on port 9000.
S3RemoteStore::new(
"bucket", prefix,
Some("http://localhost:9000")
)MinIO (production)
Self-hosted S3 for on-prem or air-gapped deployments. Same API as local dev.
S3RemoteStore::new(
"bucket", prefix,
Some("https://minio.internal:9000")
)Backblaze B2
S3-compatible. Endpoint region-specific: https://s3.{region}.backblazeb2.com
S3RemoteStore::new(
"bucket", prefix,
Some("https://s3.us-west-004…")
)Custom backend (RemoteStore trait)
Any type that implements RemoteStore works as a backend. The trait is in edgestore (not edgestore-repl), so you can implement it without pulling in the replication crate.
// edgestore::RemoteStore
pub trait RemoteStore: Send + Sync {
// Required
fn upload(&self, hash: &[u8; 32], data: &[u8]) -> Result<(), EdgestoreError>;
fn download(&self, hash: &[u8; 32]) -> Result<Vec<u8>, EdgestoreError>;
fn list(&self) -> Result<Vec<[u8; 32]>, EdgestoreError>;
fn delete(&self, hash: &[u8; 32]) -> Result<(), EdgestoreError>;
// Optional — default impl returns Ok(false) / Err(InvalidOperation)
fn upload_if_absent(&self, hash: &[u8; 32], data: &[u8]) -> Result<bool, EdgestoreError>;
fn upload_aux(&self, hash: &[u8; 32], ext: &str, data: &[u8]) -> Result<(), EdgestoreError>;
fn download_aux(&self, hash: &[u8; 32], ext: &str) -> Result<Vec<u8>, EdgestoreError>;
}
// Built-in implementations
// FilesystemRemoteStore — stores segments as files in a local directory
// S3RemoteStore — AWS SDK, any S3-compatible endpoint
Implement upload_if_absent for idempotent archiving — the default impl calls upload and always returns Ok(true). The retry loop in TieredEngine uses upload_if_absent, so a correct idempotent implementation prevents double-upload on retries.