Key/value cache from .NET
connection.Kv gives typed access to RasterizedDB's Redis-compatible key/value cache over the same native connection your SQL uses: strings and counters with lifetimes, hashes, lists, sets and sorted sets, plus typed maps and object repositories on top. Use it for caching, counters, sessions and rate limits without running a second server. What the cache is and how the server is set up for it is in the key/value cache.
Using it
using RasterizedDb.Data;
await using var dataSource = new RasterizedDbDataSource("Host=127.0.0.1;Username=app;Password=change-me-now");
await using var connection = await dataSource.OpenConnectionAsync();
var kv = connection.Kv;
await kv.SetAsync("greeting", "hello", TimeSpan.FromMinutes(5));
Console.WriteLine(await kv.GetStringAsync("greeting")); // hello
long hits = await kv.IncrementAsync("hits:/home");
TimeSpan? left = await kv.TtlAsync("greeting");How it works:
connection.Kvis a lightweight value; take it whenever you need it. Each call sends oneKV …statement on that connection (two or more for the few calls that say so).- The cache needs nothing set up on the server: it starts with the first
KVstatement. It is separate per database: a connection reaches the cache of its own database (its database 0, in Redis terms). - Keys and values are bytes. Every argument is sent as hex and values come back as bytes, so any byte string works as a key or a value. Where a call takes a
string, it means the string's UTF-8 bytes. - Every method has an
…Asyncform taking an optionalCancellationToken, and a synchronous twin without the suffix (kv.Set(…),kv.Get(…)) that blocks the calling thread on its I/O. connection.Kvneeds aRasterizedDbConnection; it does not run on a data source's shared connection.
Not transactional. A KV statement takes effect when it runs. It is not part of a SQL transaction open on the connection, and a later ROLLBACK does not undo it. No two calls here are atomic together: the native protocol has no MULTI/EXEC.
Lifetimes (TTL)
A TimeSpan? ttl argument sets a lifetime with millisecond precision (PX); the shortest is one millisecond, and null sets none.
| call | command | returns |
|---|---|---|
ExpireAsync(key, TimeSpan ttl) | PEXPIRE | true, or false when the key does not exist |
PersistAsync(byte key) | PERSIST | true when a lifetime was removed |
TtlAsync(key) | PTTL | the time left, or null when the key has no lifetime or does not exist |
Strings, counters and keys
In the tables below, "key" means either a string or a ReadOnlySpan<byte> overload unless the call says "byte key", which has only the bytes form (pass a string as Encoding.UTF8.GetBytes(…)).
| call | command | returns |
|---|---|---|
GetAsync(key) | GET | byte[]?: null when the key has no value |
GetStringAsync(string key) | GET | string?, decoded as UTF-8 |
SetAsync(key, value, TimeSpan? ttl = null) | SET [PX ms] | nothing. value is a string or ReadOnlySpan<byte>. |
SetIfAbsentAsync(key, value, TimeSpan? ttl = null) | SET … NX [PX ms] | bool: whether it was set |
GetManyAsync(IReadOnlyList<byte[]> keys) | MGET | List<byte[]?>, in the keys' order |
SetManyAsync(IReadOnlyList<KeyValuePair<byte[], byte[]>> pairs) | MSET | nothing |
DeleteAsync(key), DeleteAsync(IReadOnlyList<byte[]> keys) | DEL | long: how many keys were removed |
ExistsAsync(key) | EXISTS | bool |
IncrementAsync(key, long by = 1) | INCRBY | long: the new value. A missing key counts from 0. |
KeysAsync(pattern) | SCAN … MATCH pattern COUNT 500, repeated until done | List<byte[]>: every matching key. pattern is a glob (*, ?, [a-z]), as a string or ReadOnlyMemory<byte>. One command per 500 keys. |
using System.Text;
if (await kv.SetIfAbsentAsync("lock:report", Environment.MachineName, TimeSpan.FromSeconds(30)))
{
try
{
// only one process gets here at a time
}
finally
{
await kv.DeleteAsync("lock:report");
}
}
foreach (var key in await kv.KeysAsync("session:*"))
{
Console.WriteLine(Encoding.UTF8.GetString(key));
}Hashes
| call | command | returns |
|---|---|---|
HashSetAsync(string key, string field, string value) | HSET | long: fields newly added |
HashSetAsync(byte key, IReadOnlyList<KeyValuePair<byte[], byte[]>> fields) | HSET | long |
HashGetAsync(key, field) | HGET | byte[]? |
HashGetAllAsync(key) | HGETALL | List<KeyValuePair<byte[], byte[]>> |
HashDeleteAsync(byte key, IReadOnlyList<byte[]> fields) | HDEL | long: fields removed |
HashIncrementAsync(byte key, byte field, long by = 1) | HINCRBY | long: the new value |
Lists
All take a byte key.
| call | command | returns |
|---|---|---|
ListRightPushAsync(key, IReadOnlyList<byte[]> values) | RPUSH | long: the list's new length |
ListLeftPushAsync(key, IReadOnlyList<byte[]> values) | LPUSH | long |
ListLeftPopAsync(key) | LPOP | byte[]?: null when the list is empty |
ListRightPopAsync(key) | RPOP | byte[]? |
ListRangeAsync(key, long start, long stop) | LRANGE | List<byte[]> |
ListLengthAsync(key) | LLEN | long |
Sets
All take a byte key.
| call | command | returns |
|---|---|---|
SetAddAsync(key, IReadOnlyList<byte[]> members) | SADD | long: members newly added |
SetRemoveAsync(key, IReadOnlyList<byte[]> members) | SREM | long: members removed |
SetContainsAsync(key, member) | SISMEMBER | bool |
SetMembersAsync(key) | SMEMBERS | List<byte[]> |
SetCountAsync(key) | SCARD | long |
Sorted sets
All take a byte key.
| call | command | returns |
|---|---|---|
SortedSetAddAsync(key, IReadOnlyList<KeyValuePair<byte[], double>> members) | ZADD | long: members newly added |
SortedSetScoreAsync(key, member) | ZSCORE | double?: null when the member is not there |
SortedSetRangeAsync(key, long start, long stop, bool descending = false) | ZRANGE … [REV] WITHSCORES | List<KeyValuePair<byte[], double>>, by rank |
SortedSetRemoveAsync(key, IReadOnlyList<byte[]> members) | ZREM | long: members removed |
SortedSetIncrementAsync(key, member, double by) | ZINCRBY | double: the new score |
using System.Text;
byte[] board = Encoding.UTF8.GetBytes("leaderboard");
await kv.SortedSetAddAsync(board, [new(Encoding.UTF8.GetBytes("ada"), 1500), new(Encoding.UTF8.GetBytes("bob"), 1320)]);
foreach (var (member, score) in await kv.SortedSetRangeAsync(board, 0, 9, descending: true))
{
Console.WriteLine($"{Encoding.UTF8.GetString(member)} {score}");
}Any other command
CommandAsync(command, IEnumerable<ReadOnlyMemory<byte>> arguments) sends any cache command by name, each argument as bytes, and returns the data reader of its answer. The answer's columns depend on the command (a value column for most, field/value for HGETALL, member/score for scored replies); the key/value cache lists them and every command the cache has.
using System.Text;
await using var reader = await kv.CommandAsync(
"GETRANGE",
[Encoding.UTF8.GetBytes("greeting"), Encoding.UTF8.GetBytes("0"), Encoding.UTF8.GetBytes("3")]);
if (await reader.ReadAsync())
{
Console.WriteLine(Encoding.UTF8.GetString(reader.GetFieldValue<byte[]>(0))); // hell
}The command name must be letters, digits and _. Commands that need a connection of their own (MULTI/EXEC, SUBSCRIBE, SELECT, AUTH, CLIENT, MOVE) are refused here; use a Redis client on the server's Redis port for those.
Typed maps
kv.Map<TKey, TValue>(prefix) is a typed view of the keys under prefix:. Keys are stored as prefix:<key as text>; values as text for scalar types and as JSON (System.Text.Json) for anything else:
var sessions = kv.Map<Guid, Session>("sessions");
var id = Guid.NewGuid();
await sessions.SetAsync(id, new Session(7, "ada"), TimeSpan.FromHours(1));
Session? session = await sessions.GetAsync(id);
var (found, value) = await sessions.TryGetAsync(id);
var hits = kv.Map<string, long>("hits");
await hits.IncrementAsync("/index");
public sealed record Session(long UserId, string Name);| call | returns |
|---|---|
GetAsync(key) | TValue?: the type's default when the key has no value |
TryGetAsync(key) | (bool Found, TValue Value) |
SetAsync(key, value, TimeSpan? ttl = null) | nothing |
SetIfAbsentAsync(key, value, TimeSpan? ttl = null) | bool: whether it was set |
RemoveAsync(key) | bool: whether it existed |
ContainsAsync(key) | bool |
ExpireAsync(key, ttl), TtlAsync(key) | as for plain keys |
IncrementAsync(key, long by = 1) | long: the new value (for integer values) |
GetManyAsync(IReadOnlyList<TKey> keys) | List<TValue?> in one MGET |
KeysAsync() | List<TKey>: every key of the map, by SCAN (one command per 500 keys) |
ClearAsync() | long: keys removed (a SCAN, then a DEL per 500 keys; not atomic). Refused on a map with an empty prefix. |
FullKey(key) | byte[]: the key as stored |
Query() | a query; see below |
Scalar types, stored as their text: the numeric types, bool (t/f), string (UTF-8), char, Guid, byte[] (its bytes), enums (their number), decimal, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, Int128, BigInteger and RasterizedDbInterval. Every other type is JSON; pass JsonSerializerOptions as the second argument of Map, or a JsonTypeInfo<TValue> from a source-generated context for trimmed and AOT applications.
A null value is refused (ArgumentNullException): remove the key instead. A UTC or local DateTime is stored as its UTC time with no zone (an Unspecified one as written), so every DateTime reads back with Kind Unspecified; call DateTime.SpecifyKind(value, DateTimeKind.Utc) after reading if you need the kind.
An empty prefix (kv.Map<string, string>("")) maps the whole keyspace.
Queries over a map
var scores = kv.Map<string, int>("scores");
int players = await scores.Query().CountAsync();
List<string> aNames = await scores.Query().Prefix("a").KeysAsync();
var top = await scores.Query().Where((_, score) => score > 20).Take(10).ToListAsync();
long removed = await scores.Query().Where((_, score) => score <= 10).RemoveAsync();| member | effect |
|---|---|
.Prefix(text) | Only keys starting with text after the map's own prefix. Glob characters in it are matched literally. |
.Pattern(glob) | Only keys matching a glob after the map's own prefix. |
.WhereKey(Func<TKey, bool>) | Keeps keys the function accepts, before any value is fetched. |
.Where(Func<TKey, TValue, bool>) | Keeps entries the function accepts. |
.Take(n) | At most n entries. |
.Lenient() | Skips keys and values that do not read as TKey/TValue, instead of throwing InvalidCastException. |
ToListAsync() | List<KeyValuePair<TKey, TValue>> |
KeysAsync() | List<TKey>; fetches no values unless Where needs them |
CountAsync() | int |
RemoveAsync() | long: entries removed (a DEL per 500 keys; not atomic) |
The server matches the key pattern (SCAN); values are fetched 500 at a time and the Where filters run in your process. A query is not a snapshot: an entry removed between the scan and its fetch is left out.
Object repositories
kv.Repository<T, TKey>(keySelector, prefix) stores objects as hashes, one field per public read-write property, under prefix:<key>. A single field can then be read or changed without the rest:
var visitors = kv.Repository<Visitor, Guid>(v => v.Id); // prefix "visitor"
var id = Guid.NewGuid();
await visitors.SaveAsync(new Visitor { Id = id, Name = "Ada", Visits = 1, Roles = ["admin"] }, TimeSpan.FromDays(30));
await visitors.IncrementAsync(id, nameof(Visitor.Visits));
await visitors.SetFieldAsync(id, nameof(Visitor.Name), "Ada L.");
Visitor? visitor = await visitors.GetAsync(id);
public sealed class Visitor
{
public Guid Id { get; set; }
public string Name { get; set; } = "";
public long Visits { get; set; }
public DateTime? LastSeen { get; set; }
public string[] Roles { get; set; } = [];
}| call | effect |
|---|---|
SaveAsync(item, TimeSpan? ttl = null) | Writes every property as a field (HSET). A null property's field is removed, so it reads back as null. With a ttl, or when a property is null, it takes more than one command and is not atomic. |
GetAsync(key) | The object, or null when nothing is stored. Fields that match no property are ignored. |
SetFieldAsync(key, property, object value) | Changes one field. An unknown property name throws ArgumentException. |
IncrementAsync(key, property, long by = 1) | Adds to a numeric field in place (HINCRBY) and returns its new value. |
RemoveAsync(key) | bool: whether it existed. |
ContainsAsync(key) | bool. |
ExpireAsync(key, ttl) | bool: false when it does not exist. |
T must be a class with a public parameterless constructor. The prefix defaults to the type's name in lower case. Properties of the scalar types listed for maps are stored as text (without Int128, BigInteger and RasterizedDbInterval); any other property type, such as string[] above, is stored as JSON.
Privileges
Commands that administer the server rather than the data (CONFIG SET, CONFIG RESETSTAT, SAVE, BGSAVE, FLUSHALL) need a superuser. Everything else, including every typed call on this page, is open to any role that can log in. These administrative commands are only reachable here through CommandAsync.
Limits
- No transactions: nothing here is undone by a SQL
ROLLBACK, and no two calls are atomic together. - No
MULTI/EXEC,WATCH, pub/sub (SUBSCRIBE) or blocking pops with a wait: a blocking pop over SQL answers at once. Use a Redis client on the server's Redis port (--kv-port) for those; see the key/value cache. - Map queries and
KeysAsyncwalk the keyspace withSCAN, so their cost grows with the number of matching keys. - A
DateTimein a map or repository reads back withKindUnspecified.