NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / C# / .NET CLIENT / KEY/VALUE CACHE FROM .NET

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

csharp
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.Kv is a lightweight value; take it whenever you need it. Each call sends one KV … 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 KV statement. 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 …Async form taking an optional CancellationToken, and a synchronous twin without the suffix (kv.Set(…), kv.Get(…)) that blocks the calling thread on its I/O.
  • connection.Kv needs a RasterizedDbConnection; 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.

callcommandreturns
ExpireAsync(key, TimeSpan ttl)PEXPIREtrue, or false when the key does not exist
PersistAsync(byte key)PERSISTtrue when a lifetime was removed
TtlAsync(key)PTTLthe 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(…)).

callcommandreturns
GetAsync(key)GETbyte[]?: null when the key has no value
GetStringAsync(string key)GETstring?, 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)MGETList<byte[]?>, in the keys' order
SetManyAsync(IReadOnlyList<KeyValuePair<byte[], byte[]>> pairs)MSETnothing
DeleteAsync(key), DeleteAsync(IReadOnlyList<byte[]> keys)DELlong: how many keys were removed
ExistsAsync(key)EXISTSbool
IncrementAsync(key, long by = 1)INCRBYlong: the new value. A missing key counts from 0.
KeysAsync(pattern)SCAN … MATCH pattern COUNT 500, repeated until doneList<byte[]>: every matching key. pattern is a glob (*, ?, [a-z]), as a string or ReadOnlyMemory<byte>. One command per 500 keys.
csharp
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

callcommandreturns
HashSetAsync(string key, string field, string value)HSETlong: fields newly added
HashSetAsync(byte key, IReadOnlyList<KeyValuePair<byte[], byte[]>> fields)HSETlong
HashGetAsync(key, field)HGETbyte[]?
HashGetAllAsync(key)HGETALLList<KeyValuePair<byte[], byte[]>>
HashDeleteAsync(byte key, IReadOnlyList<byte[]> fields)HDELlong: fields removed
HashIncrementAsync(byte key, byte field, long by = 1)HINCRBYlong: the new value

Lists

All take a byte key.

callcommandreturns
ListRightPushAsync(key, IReadOnlyList<byte[]> values)RPUSHlong: the list's new length
ListLeftPushAsync(key, IReadOnlyList<byte[]> values)LPUSHlong
ListLeftPopAsync(key)LPOPbyte[]?: null when the list is empty
ListRightPopAsync(key)RPOPbyte[]?
ListRangeAsync(key, long start, long stop)LRANGEList<byte[]>
ListLengthAsync(key)LLENlong

Sets

All take a byte key.

callcommandreturns
SetAddAsync(key, IReadOnlyList<byte[]> members)SADDlong: members newly added
SetRemoveAsync(key, IReadOnlyList<byte[]> members)SREMlong: members removed
SetContainsAsync(key, member)SISMEMBERbool
SetMembersAsync(key)SMEMBERSList<byte[]>
SetCountAsync(key)SCARDlong

Sorted sets

All take a byte key.

callcommandreturns
SortedSetAddAsync(key, IReadOnlyList<KeyValuePair<byte[], double>> members)ZADDlong: members newly added
SortedSetScoreAsync(key, member)ZSCOREdouble?: null when the member is not there
SortedSetRangeAsync(key, long start, long stop, bool descending = false)ZRANGE … [REV] WITHSCORESList<KeyValuePair<byte[], double>>, by rank
SortedSetRemoveAsync(key, IReadOnlyList<byte[]> members)ZREMlong: members removed
SortedSetIncrementAsync(key, member, double by)ZINCRBYdouble: the new score
csharp
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.

csharp
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:

csharp
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);
callreturns
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

csharp
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();
membereffect
.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:

csharp
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; } = [];
}
calleffect
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 KeysAsync walk the keyspace with SCAN, so their cost grows with the number of matching keys.
  • A DateTime in a map or repository reads back with Kind Unspecified.
✓ page rendered in 157 µs axum + tera + htmx · no other javascript