Microsoft Garnet

repository·main·Indexed 11 days ago

https://github.com/microsoft/garnet

A high-performance, cross-platform remote cache-store built on .NET that is compatible with the Redis RESP protocol. Designed for low latency and high throughput in large-scale cloud applications, it includes tools for RESP and micro-benchmarking, support for Tsavorite devices, and Kubernetes deployment via Helm charts.

Tokens
125.9K
Snippets
326
Records
566
Agent score
94%

What's inside Garnet

  1. Introduction to FASTER Log and FASTER KV

    main

    The FASTER project provides two primary artifacts for managing large application state with high performance and resilience:

    • FASTER Log: A high-performance concurrent persistent recoverable log, iterator, and random reader library written in C#. It is designed for frequent commit operations at low latency and can saturate disk bandwidth. It supports both synchronous and asynchronous interfaces, handles disk errors, and includes checksums.

    • FASTER KV: A concurrent key-value store and cache available in both C# and C++. It is optimized for point lookups and heavy updates. It supports datasets larger than available memory by leveraging fast external storage (local or cloud) and provides consistent recovery via a fast non-blocking checkpointing technique, allowing users to trade off performance for commit latency.

  2. What is Azure Cosmos DB Garnet Cache?

    main

    Azure Cosmos DB Garnet Cache is a fully managed, high-performance caching service built on the Garnet remote cache-store. It is designed for enterprise-grade reliability, security, and scalability.

    Unlike traditional single-threaded caches, Garnet uses a shared-everything architecture within nodes, where all threads directly access a single shared memory space. This allows for:

    • Ultra-Low Latency: Median (P50) latency < 1 ms; 99th percentile (P99) latency at 3 ms.
    • High Throughput: Supports millions of operations per second with linear scalability.
    • Scalability: Supports vertical and horizontal scaling, and configurable replication.
    • Data Persistence: Optional durability via non-blocking append-only file (AOF) logging and Redis Database (RDB) snapshots.
  3. Introduction to Tsavorite storage layer

    main

    Tsavorite is the storage layer for Garnet. It is a fork of the FASTER project and provides high-performance database features designed for scalability and durability.

    Key features include:

    • Thread Scalability: Optimized for high-concurrency workloads.
    • Tiered Storage: Support for multiple storage tiers including memory, SSD, and cloud storage.
    • Durability & Recovery: Includes fast non-blocking checkpointing, recovery mechanisms, and operation logging.
    • Concurrency Control: Supports multi-key locking and transaction support.
    • Resource Management: Improved memory management and space reuse capabilities.
  4. Overview of Garnet features and APIs

    main

    Garnet is a high-performance, cross-platform remote cache-store built on .NET. It supports a wide range of operations:

    • Raw Strings: GET, SET, and key expiration.
    • Analytical Operations: HyperLogLog and Bitmap.
    • Object Operations: Sorted Sets, Lists, Sets, Hashes, and Geo.
    • Transactions: Supports client-side RESP transactions and server-side stored procedures/modules written in C#.
    • Scripting: Supports Lua scripts.
    • Advanced Features (Preview):
      • Vector Sets: Approximate nearest-neighbor search using the DiskANN algorithm.
      • Range Index: Secondary range and equality indexes over keys using Bf-Tree.
  5. Choose an extensibility method in Garnet

    main

    Garnet provides five primary ways to extend its core functionality depending on your data model and execution requirements:

    • Custom Raw String Command: Use this when you need to operate on a single key containing raw string values stored in Garnet's unified store.
    • Custom Object Command: Use this to expose commands that perform operations on custom data types (object values) within the unified store.
    • Custom Transaction: Use this when you need to execute a block of multiple commands atomically. This ensures that the entire block succeeds or fails as a single unit.
    • Custom Procedure: Use this to invoke multiple commands in a single block where atomicity is not required. Commands are executed non-transactionally, behaving as if they were issued individually by a client.
    • Module: Use this to package related extension commands, procedures, and transactions into a single binary that can be loaded into Garnet.
  6. Garnet Core API capabilities

    main

    Garnet provides a comprehensive API surface compatible with common key-value store patterns, including:

    • Raw Strings: Support for Get and Set variants, including key expiration.
    • Data Structures: Support for List, Hash, Set, Sorted Set, and Geo types.
    • Analytics: Specialized APIs for Hyperloglog and Bitmap operations.
    • Transactions: Client-side transaction API using MULTI/EXEC.
    • Messaging: Publish/Subscribe capabilities.
    • Management: Admin operations and Access Control List (ACL) features.
  7. Understand API compatibility for Azure Cosmos DB Garnet Cache

    main

    Azure Cosmos DB Garnet Cache is compatible with Redis clients and supports a subset of Redis data types and commands.

    Key Constraints:

    • Maximum Key-Value Size: 32MB.
    • Performance Recommendation: For the lowest latency, aim to keep key-value pairs around 1KB.

    The implementation follows the open-source Garnet command set, covering various categories including CLIENT, CLUSTER, HASH, STRING, and more.

  8. Understand Garnet API coverage and extensibility

    main

    Garnet provides compatibility with a large subset of the Redis REST API surface. While the supported command list is continuously expanding, you can check the current support status for specific commands in the api-compatibility.md documentation.

    Beyond standard Redis commands, Garnet features a custom operator framework. This allows you to register custom C# data structures and read-modify-write operations directly on the server, which can then be accessed via an extension of the RESP (Redis Serialization Protocol).

  9. Overview of Vector Sets in Garnet

    main

    Garnet provides partial support for Vector Sets, which are implemented using the DiskANN project.

    Mental Model

    A Vector Set consists of:

    1. An Index Key: A single key that stores metadata and a pointer to the underlying DiskANN data structure. This is the only key visible to the user.
    2. Element Keys: Multiple keys that store the actual vectors, quantized vectors, attributes, etc.

    To prevent user commands from accidentally overwriting element data, Garnet stores element keys in different namespaces derived from the index's Context value. This allows standard commands like SET to work on the same key names without interfering with the Vector Set's internal storage.

  10. Understand the FreeRecordPool and FreeRecordBin hierarchy

    main

    The FreeList mechanism is organized into a three-tier hierarchy designed for high-concurrency reuse of deleted records:

    1. FreeRecordPool: The top-level manager that maintains multiple bins and uses a size index (a cache-aligned vector of integers) to quickly determine which bin should handle an Enqueue or Dequeue request.
    2. FreeRecordBins: Multiple bins corresponding to the RevivificationBin definitions in your settings. Each bin manages a specific range of record sizes. Bins use a segmented circular buffer approach to balance search efficiency and concurrency.
    3. FreeRecord: The individual units stored within bins. Each FreeRecord contains a free log address and the epoch in which it was freed. The record's data is stored as a long containing the 48-bit address and 16-bit size (for records $\le 2^{16}$ bytes).
  11. Understand Client Redirection in Garnet Cluster

    main

    Clients can connect to any node in the cluster. The node receiving the request calculates the relevant hashlot and responds based on the following logic:

    • Slot owned by receiving node: Performs the operation normally.
    • Slot owned by another node: Responds with -MOVED <slot> <address> <port>.
    • Receiving node is a replica: Serves read requests for its primary's slots; redirects write requests via -MOVED.
    • Slot is migrating:
      • If the key exists: Reads are normal; writes return -MIGRATING.
      • If the key does not exist: Both reads and writes return -ASK <slot> <address> <port>.
    • Target of migration: If the receiving node is the target of a migration, requests are only served if the client previously issued an ASKING command. Note that using ASKING does not ensure write safety; clients must handle this with care.
  12. Manage network memory with LimitedFixedBufferPool

    main

    Garnet uses the LimitedFixedBufferPool class to efficiently manage memory allocations and prevent frequent GC pressure. This pool provides thread-safe memory segments of varying sizes using an array of concurrent queues.

    Key Characteristics

    • Size Management: Supports memory segments that are powers of two and greater than or equal to the minimum allocation size.
    • Thread Safety: Designed for multi-threaded scenarios using concurrent queues.
    • Lifecycle: The pool is IDisposable and must be disposed of to release allocated memory segments.

    Core Methods

    • Get(size): Allocates a memory segment of the requested size and returns a PoolEntry object.
    • Return(PoolEntry): Returns a memory segment to the pool for reuse.

    PoolEntry Class

    PoolEntry is the object returned by the pool representing an allocated memory segment. It provides the necessary methods to manage and reuse the segment once the operation is complete.