Client Lifecycle
Clustron DKV clients are designed to be reused, efficient, and safe for concurrent use.
Understanding how to manage the client lifecycle is important for building reliable applications.
Creating the Clientβ
Clients are obtained through IDkvClientProvider:
var client = await provider.GetAsync("default");
- The provider manages creation and reuse
- You should not create clients manually
Reuse the Clientβ
Clients are intended to be reused.
Create once β reuse everywhere
Recommended Patternβ
public class OrderService
{
private readonly IDkvClient _client;
public OrderService(IDkvClientProvider provider)
{
_client = provider.GetAsync("orders").GetAwaiter().GetResult();
}
}
Thread Safetyβ
Clients are thread-safe.
Multiple threads β same client β safe
You can:
- Share the same client across threads
- Use it in parallel operations
- Use it in async workflows
Do NOT Create Clients Per Operationβ
Avoid this pattern:
var client = await provider.GetAsync("default");
await client.PutAsync("key", "value");
Repeated creation leads to:
- unnecessary overhead
- connection churn
- reduced performance
Disposalβ
Clientβ
You typically do not need to dispose the client manually.
- Lifecycle is managed by the provider
- Reused across the application
Transactionsβ
Transactions must be disposed:
await using var tx = await client.BeginTransactionAsync();
Watch Streamsβ
Watch operations should be stopped when no longer needed:
await foreach (var evt in client.Watch.WatchKeyAsync("key"))
{
// use cancellation token or break to stop
}
Application Lifetimeβ
Clients should live as long as your application:
- Register once at startup
- Reuse across services
- Dispose automatically when application shuts down
Multiple Storesβ
If you use multiple stores:
var orders = await provider.GetAsync("orders");
var cache = await provider.GetAsync("cache");
Each client is:
- independently managed
- reusable
- thread-safe
Best Practicesβ
- Resolve client once and reuse
- Avoid creating clients inside loops
- Use provider for lifecycle management
- Dispose transactions properly
- Keep long-running operations outside transactions
Key Takeawayβ
Client = shared, reusable, long-lived
You do not treat it like a short-lived object.
Whatβs Nextβ
π Explore Samples for real-world usage