| title | Time-Based Sharding in Encina |
|---|---|
| layout | default |
| parent | Features |
This guide explains how to use time-based sharding to partition data by time periods with automatic tier lifecycle management. Shards progress through storage tiers (Hot, Warm, Cold, Archived) as data ages, enabling cost-optimized storage and transparent query routing.
- Overview
- When to Use Time-Based Sharding
- Configuration
- Shard Periods
- Tier Lifecycle
- Routing
- Automatic Tier Transitions
- Auto-Shard Creation
- Archival and Retention
- Health Checks
- Observability
- Error Handling
- Operations Guide
- Troubleshooting
- FAQ
Time-based sharding partitions data into shards based on time periods. Each shard covers a contiguous range (daily, weekly, monthly, quarterly, or yearly) and belongs to a storage tier that reflects how actively the data is used:
flowchart LR
HOT["HOT<br/>(writes + reads)<br/>SSD / Memory"]
WARM["WARM<br/>(read-only, recent data)<br/>Standard"]
COLD["COLD<br/>(read-only, infrequent)<br/>HDD / Compressed"]
ARCHIVED["ARCHIVED<br/>(read-only, long-term)<br/>S3 / Blob"]
HOT -- "30 days" --> WARM -- "90 days" --> COLD -- "365 days" --> ARCHIVED
Only Hot-tier shards accept writes. The TierTransitionScheduler background service automatically transitions shards between tiers based on configurable age thresholds.
| Scenario | Single Shard | Hash Sharding | Time-Based Sharding |
|---|---|---|---|
| Small dataset, all recent | |||
| Uniform access across all data | |||
| Access patterns skew heavily by recency | |||
| Compliance requires data retention policies | |||
| Cost optimization for cold/archived data | |||
| High-volume event/log ingestion |
Use time-based sharding when:
- Data has a natural timestamp (events, logs, transactions, sensor readings)
- Recent data is accessed frequently, older data rarely
- You want to reduce storage costs by moving old data to cheaper tiers
- Compliance or retention policies require archiving data after a specific age
- You need to delete old data cleanly (drop an entire shard instead of row-by-row deletes)
Common use cases:
- Audit logs: Monthly shards with 1-year archive policy
- IoT sensor data: Daily shards with aggressive tier transitions
- E-commerce orders: Monthly shards, warm after 30 days, cold after 90 days
- Financial transactions: Quarterly shards with yearly archival
// 1. Configure the time-based sharding options
services.Configure<TimeBasedShardingOptions>(options =>
{
options.Enabled = true;
options.Period = ShardPeriod.Monthly;
options.CheckInterval = TimeSpan.FromMinutes(30);
options.ShardIdPrefix = "orders";
options.ConnectionStringTemplate = "Server=hot;Database=orders_{0}";
options.Transitions =
[
new TierTransition(ShardTier.Hot, ShardTier.Warm, TimeSpan.FromDays(30)),
new TierTransition(ShardTier.Warm, ShardTier.Cold, TimeSpan.FromDays(90)),
new TierTransition(ShardTier.Cold, ShardTier.Archived, TimeSpan.FromDays(365)),
];
});
// 2. Register the tier store and archiver
services.AddSingleton<ITierStore, InMemoryTierStore>();
services.AddSingleton<IShardArchiver, ShardArchiver>();
// 3. Register the background scheduler
services.AddHostedService<TierTransitionScheduler>();| Option | Type | Default | Description |
|---|---|---|---|
Enabled |
bool |
true |
Whether the scheduler runs |
Period |
ShardPeriod |
Monthly |
Time granularity for shard boundaries |
WeekStart |
DayOfWeek |
Monday |
First day of week (ISO 8601), only for Weekly |
CheckInterval |
TimeSpan |
1 hour |
How often the scheduler checks for transitions |
Transitions |
IReadOnlyList<TierTransition> |
[] |
Age-based tier transition rules |
EnableAutoShardCreation |
bool |
true |
Whether to pre-create shards for upcoming periods |
ShardCreationLeadTime |
TimeSpan |
1 day |
How far ahead to create the next shard |
ShardIdPrefix |
string |
"shard" |
Prefix for auto-generated shard IDs |
ConnectionStringTemplate |
string? |
null |
Template with {0} placeholder for period label |
Auto-generated shard IDs follow the pattern {ShardIdPrefix}-{PeriodLabel}:
| Period | Example Shard ID |
|---|---|
| Daily | orders-2026-01-15 |
| Weekly | orders-2026-W03 |
| Monthly | orders-2026-01 |
| Quarterly | orders-2026-Q1 |
| Yearly | orders-2026 |
The ShardPeriod enum controls how time is divided into shard boundaries:
public enum ShardPeriod
{
Daily, // One shard per calendar day
Weekly, // One shard per ISO 8601 week (Mon-Sun)
Monthly, // One shard per calendar month
Quarterly, // One shard per quarter (Q1: Jan-Mar, etc.)
Yearly // One shard per calendar year
}Choosing a period:
| Factor | Shorter Periods (Daily) | Longer Periods (Yearly) |
|---|---|---|
| Number of shards | More | Fewer |
| Shard size | Smaller | Larger |
| Scatter-gather queries | More shards to query | Fewer shards to query |
| Archival granularity | Fine-grained | Coarse-grained |
| Drop-shard cleanup | Low-cost deletes | Larger deletes |
Recommendation: Start with Monthly for most workloads. Use Daily for high-volume data (IoT, logs) and Quarterly or Yearly for lower-volume data with long retention.
| Tier | Writes | Reads | Typical Storage | Use Case |
|---|---|---|---|---|
| Hot | Yes | Yes | SSD, in-memory cache | Current period's active data |
| Warm | No | Yes | Standard SSD/HDD | Recent historical data |
| Cold | No | Yes | HDD, compressed | Infrequent access, compliance |
| Archived | No | Yes | S3, Azure Blob, tape | Long-term retention |
Transitions are defined as TierTransition records with three properties:
// Transition shards from Hot to Warm after 30 days past the period end
new TierTransition(ShardTier.Hot, ShardTier.Warm, TimeSpan.FromDays(30))FromTier: The current tier (must be less thanToTier)ToTier: The target tier (must be greater thanFromTier)AgeThreshold: Time since the shard's period ended before transitioning
Rules:
- Transitions must move forward: Hot -> Warm -> Cold -> Archived
- You can skip tiers (e.g., Hot -> Archived)
- Backward transitions are rejected at construction time
- Same-tier transitions are rejected at construction time
- Zero or negative age thresholds are rejected
flowchart LR
subgraph PeriodActive["Active Period"]
A1["HOT<br/>(write + read)"]
end
subgraph PeriodEnd["Period Ends"]
A2["HOT<br/>(read + write)"]
end
subgraph After30["+ 30 days"]
B["WARM<br/>(read-only)"]
end
subgraph After90["+ 90 days"]
C["COLD<br/>(read-only)"]
end
subgraph After365["+ 365 days"]
D["ARCHIVED<br/>(read-only)"]
end
A1 --> A2 --> B --> C --> D
The ITimeBasedShardRouter routes operations to shards based on timestamps:
// Route a read to the appropriate shard
var result = await router.RouteByTimestampAsync(DateTime.UtcNow);
result.Match(
Right: shardId => logger.LogInformation("Read from {ShardId}", shardId),
Left: error => logger.LogError("Routing failed: {ErrorCode}", error.GetCode().IfNone("encina.unknown")));
// Route a write (enforces Hot tier)
var writeResult = await router.RouteWriteByTimestampAsync(DateTime.UtcNow);
writeResult.Match(
Right: shardId => logger.LogInformation("Writing to {ShardId}", shardId),
Left: error => logger.LogError("Write failed: {ErrorCode}", error.GetCode().IfNone("encina.unknown")));Log the error code, not error.Message: messages can carry personal data. Pass exceptions to loggers as ex.ForLogging() (namespace Encina.Diagnostics), which keeps the type and stack trace and drops the message.
Query across multiple shards using time ranges:
// Get all shards covering Q1 2026
var shards = await router.GetShardsInRangeAsync(
new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc),
new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc));
shards.Match(
Right: ids => ids.ToList().ForEach(id =>
logger.LogInformation("Query shard: {ShardId}", id)),
Left: error => logger.LogError("Range query failed: {ErrorCode}", error.GetCode().IfNone("encina.unknown")));Check a shard's current tier and metadata:
// Get the tier
Either<EncinaError, ShardTier> tier = router.GetShardTier("orders-2026-01");
// Get full metadata
Either<EncinaError, ShardTierInfo> info = router.GetShardTierInfo("orders-2026-01");
info.Match(
Right: ti => logger.LogInformation(
"Shard {Id}: {Tier}, Period {Start}-{End}, ReadOnly={RO}",
ti.ShardId, ti.CurrentTier, ti.PeriodStart, ti.PeriodEnd, ti.IsReadOnly),
Left: error => logger.LogError("Shard not found: {ErrorCode}", error.GetCode().IfNone("encina.unknown")));The TimeBasedShardRouter uses a sorted array of TimeBasedShardEntry records with binary search for O(log n) routing. Period boundaries are pre-computed at construction time using PeriodBoundaryCalculator, and tier metadata is stored in a FrozenDictionary for fast lookup.
The TierTransitionScheduler is a BackgroundService that runs on a configurable interval:
- Each tick, it resolves
ITierStoreandIShardArchiverfrom a scopedIServiceProvider - For each configured
TierTransition, it queries the tier store for shards due for transition - For each due shard, it calls
IShardArchiver.TransitionTierAsync() - Successes and failures are logged individually, with totals per tick
Behavior:
- The scheduler never crashes. Exceptions are caught, logged, and retried on the next tick
- Each transition is independent: a failure in one shard does not block others
- The scheduler uses
TimeProviderfor testability (injectMicrosoft.Extensions.Time.Testing.FakeTimeProviderin tests) - Scoped dependencies are resolved fresh on each tick for database context compatibility
Example log output:
[INF] Time-based shard tier transition scheduler started (interval: 00:30:00, rules: 3)
[INF] Tier transition check started
[INF] Transitioning shard 'orders-2025-10' from Hot to Warm
[INF] Tier transition succeeded for shard 'orders-2025-10' to Warm
[INF] Tier transition check completed: 1 succeeded, 0 failed
When EnableAutoShardCreation is true, the scheduler pre-creates shards for upcoming time periods:
- Computes the current period's end date using
PeriodBoundaryCalculator - Checks if
today + ShardCreationLeadTime >= currentPeriodEnd - If within the lead time window:
- Generates the shard ID:
{ShardIdPrefix}-{PeriodLabel} - Generates the connection string from
ConnectionStringTemplate - Checks if the shard already exists (idempotent)
- Creates a new Hot-tier
ShardTierInfoin the tier store
- Generates the shard ID:
Requirements:
ConnectionStringTemplatemust be set (uses{0}for period label)- The
IShardFallbackCreatorinterface is available for database-level shard provisioning
Race condition handling: If multiple instances attempt to create the same shard simultaneously, the ArgumentException from duplicate shard IDs is caught and logged as a skip, not an error.
The IShardArchiver.ArchiveShardAsync() method exports shard data to external storage:
var result = await archiver.ArchiveShardAsync(
"orders-2024-01",
new ArchiveOptions("s3://archive-bucket/orders/2024-01"));
result.Match(
Right: _ => logger.LogInformation("Archive complete"),
Left: error => logger.LogError("Archive failed: {ErrorCode}", error.GetCode().IfNone("encina.unknown")));Note: The default
ShardArchiverimplementation is a no-op for archival. Actual data export requires a provider-specific implementation that integrates with your storage backend (S3, Azure Blob, etc.).
Read-only state is enforced at two levels:
- Application level: The
ITimeBasedShardRouterchecks theIsReadOnlyflag inShardTierInfoand returns error codeencina.sharding.shard_read_onlyfor write attempts - Database level (optional): Register an
IReadOnlyEnforcerto apply database-level restrictions (e.g.,ALTER DATABASE SET READ_ONLYon SQL Server)
// Manually enforce read-only
await archiver.EnforceReadOnlyAsync("orders-2025-10");// Delete shard data as part of a retention policy
var result = await archiver.DeleteShardDataAsync("orders-2023-01");The default implementation updates the tier store metadata only. Database-level deletion (e.g., DROP DATABASE) requires a provider-specific IShardArchiver.
Two health checks monitor the time-based sharding subsystem:
Configured via ShardCreationHealthCheckOptions:
| State | Condition |
|---|---|
| Healthy | Shards exist for both the current and next period |
| Degraded | Next period's shard is missing (within warning window) |
| Unhealthy | Current period's shard is missing |
services.Configure<ShardCreationHealthCheckOptions>(options =>
{
options.Period = ShardPeriod.Monthly;
options.ShardIdPrefix = "orders";
options.WarningWindowDays = 3; // Warn 3 days before period end
});Configured via TierTransitionHealthCheckOptions:
| State | Condition |
|---|---|
| Healthy | All shards are within expected tier age thresholds |
| Degraded | Some shards have exceeded their expected tier age |
| Unhealthy | Shards are significantly overdue (2x threshold) |
services.Configure<TierTransitionHealthCheckOptions>(options =>
{
options.MaxExpectedHotAgeDays = 35; // 1 month + 5 day buffer
options.MaxExpectedWarmAgeDays = 95; // 3 months + 5 day buffer
options.MaxExpectedColdAgeDays = 370; // 1 year + 5 day buffer
options.UnhealthyMultiplier = 2.0; // 2x threshold = unhealthy
});The TimeBasedShardingMetrics class (in Encina.OpenTelemetry) exposes six metric instruments under the Encina meter:
| Instrument | Type | Tags | Description |
|---|---|---|---|
encina.sharding.tiered.shards_per_tier |
ObservableGauge | shard.tier |
Current shard count per tier |
encina.sharding.tiered.oldest_hot_shard_age_days |
ObservableGauge | Age of oldest Hot shard (days) | |
encina.sharding.tiered.tier_transitions_total |
Counter | tier.from, tier.to |
Tier transitions executed |
encina.sharding.tiered.auto_created_shards_total |
Counter | Auto-created shard count | |
encina.sharding.tiered.queries_per_tier |
Counter | shard.tier |
Queries routed per tier |
encina.sharding.tiered.archival_duration_ms |
Histogram | db.shard.id |
Archival duration (ms) |
Key alerts to configure:
shards_per_tier{shard.tier="Hot"} == 0— No active shard for writesoldest_hot_shard_age_days > 35— Hot shard overdue for transitiontier_transitions_totalrate drop to 0 — Scheduler may be stuck
All operations return Either<EncinaError, T> following Railway Oriented Programming. Error codes specific to time-based sharding:
| Error Code | Constant | Cause |
|---|---|---|
encina.sharding.shard_read_only |
ShardingErrorCodes.ShardReadOnly |
Write attempt on a non-Hot shard |
encina.sharding.timestamp_outside_range |
ShardingErrorCodes.TimestampOutsideRange |
Timestamp doesn't match any shard period |
encina.sharding.no_time_based_shards |
ShardingErrorCodes.NoTimeBasedShards |
No shards configured in the topology |
encina.sharding.tier_transition_failed |
ShardingErrorCodes.TierTransitionFailed |
Tier transition could not be completed |
encina.sharding.archival_failed |
ShardingErrorCodes.ArchivalFailed |
Archival operation failed |
encina.sharding.retention_policy_failed |
ShardingErrorCodes.RetentionPolicyFailed |
Retention/deletion operation failed |
encina.sharding.shard_creation_failed |
ShardingErrorCodes.ShardCreationFailed |
Auto-shard creation failed |
encina.sharding.partial_key_routing_failed |
ShardingErrorCodes.PartialKeyRoutingFailed |
Partial key could not resolve shards |
var result = await router.RouteWriteByTimestampAsync(timestamp);
result.Match(
Right: shardId => { /* proceed with write */ },
Left: error =>
{
var code = error.GetCode();
code.IfSome(c =>
{
if (c == ShardingErrorCodes.ShardReadOnly)
logger.LogWarning("Shard is read-only for timestamp {Ts}", timestamp);
else if (c == ShardingErrorCodes.TimestampOutsideRange)
logger.LogError("No shard covers timestamp {Ts}", timestamp);
});
});Use IShardArchiver directly for manual tier management:
// Manually transition a shard
var result = await archiver.TransitionTierAsync("orders-2025-06", ShardTier.Archived);
// Manually enforce read-only
await archiver.EnforceReadOnlyAsync("orders-2025-06");
// Manually delete old data
await archiver.DeleteShardDataAsync("orders-2023-01");- Check the health endpoints:
/health/shard-creationand/health/tier-transitions - Watch the metrics:
shards_per_tiergauge shows the distribution across tiersoldest_hot_shard_age_daysalerts when transitions are overduetier_transitions_totalcounter confirms the scheduler is running
- Review scheduler logs: The scheduler logs each transition attempt with shard ID, source tier, and target tier
| Metric Pattern | Interpretation | Action |
|---|---|---|
shards_per_tier{Hot} increasing |
New shards being created | Normal if auto-creation is on |
shards_per_tier{Hot} > 2 |
Multiple Hot shards | Check if transitions are running |
oldest_hot_shard_age_days > threshold |
Transition overdue | Check scheduler logs for errors |
tier_transitions_total flat |
No transitions happening | Verify scheduler is enabled and running |
auto_created_shards_total flat |
No new shards created | Check ConnectionStringTemplate is set |
var tierInfo = new ShardTierInfo(
ShardId: "orders-2026-04",
CurrentTier: ShardTier.Hot,
PeriodStart: new DateOnly(2026, 4, 1),
PeriodEnd: new DateOnly(2026, 5, 1),
IsReadOnly: false,
ConnectionString: "Server=hot;Database=orders_2026-04",
CreatedAtUtc: DateTime.UtcNow);
await tierStore.AddShardAsync(tierInfo);Symptoms: oldest_hot_shard_age_days increasing, tier_transitions_total flat
- Check scheduler is enabled: Verify
TimeBasedShardingOptions.Enabled == true - Check transitions are configured: Verify
Transitionslist is not empty - Check scheduler logs: Look for
TransitionCheckErrorlog entries - Check the tier store: Verify
GetShardsDueForTransitionAsync()returns shards - Check the archiver: Verify
TransitionTierAsync()is not returning errors
Symptoms: Health check reports Degraded/Unhealthy, auto_created_shards_total flat
- Check
ConnectionStringTemplate: Must be set and contain{0}placeholder - Check
EnableAutoShardCreation: Must betrue - Check
ShardCreationLeadTime: If too short, the window may be missed between ticks - Check scheduler logs: Look for
AutoCreateFailedlog entries - Check for duplicates:
AutoCreateSkippedAlreadyExistsmeans another instance created it first (normal in multi-instance deployments)
Symptoms: Writes succeed on non-Hot shards
- Check the router: Ensure you're using
RouteWriteByTimestampAsync()(notRouteByTimestampAsync()which allows reads on all tiers) - Check
IsReadOnlyflag: Verify theShardTierInfo.IsReadOnlyistruefor non-Hot shards - Check
IReadOnlyEnforcer: If database-level enforcement is needed, register a provider-specific enforcer
Symptoms: Error code encina.sharding.timestamp_outside_range on routing
- Check shard coverage: Verify shards exist for the timestamp's time period
- Check the topology: The
TimeBasedShardRouteronly knows about shards registered in the topology - Create the missing shard: Either enable auto-creation or add the shard manually
Yes. Use compound shard keys to combine time-based routing with hash routing. See Compound Shard Keys for details.
The scheduler retries on the next tick. Transitions are idempotent: if a shard was already transitioned, the next check skips it. No data is lost.
Yes. Auto-shard creation handles race conditions via try/catch on duplicate shard IDs. Tier transitions are idempotent. However, consider using a distributed lock to avoid redundant work in multi-instance deployments.
You cannot change a shard's period boundaries after creation. Instead, create new shards with the desired period and migrate data. This is by design to maintain shard boundary consistency.
The TimeBasedShardRouter uses binary search (O(log n)) on a sorted array of shard entries, with tier metadata in a FrozenDictionary. For typical deployments with fewer than 100 shards, routing is effectively O(1) with sub-microsecond latency.
No. Read-only enforcement at the application level (via RouteWriteByTimestampAsync()) is sufficient for most use cases. Implement IReadOnlyEnforcer only if you need database-level protection (e.g., ALTER DATABASE SET READ_ONLY).
InMemoryTierStore uses ConcurrentDictionary internally and is thread-safe for all operations including AddShardAsync, UpdateTierAsync, and GetShardsDueForTransitionAsync. It is suitable for single-process deployments and testing.
- Compound Shard Keys — Multi-field routing with independent strategies
- Database Sharding Configuration — Complete sharding configuration reference
- Cross-Shard Operations — Scatter-gather and partial failure handling
- Scaling Guidance — Shard key selection and capacity planning
- ADR-010: Database Sharding — Architecture Decision Record