Skip to main content
The store package provides the core key-value storage functionality for ValKeyper, including support for expiration, replication, transactions, and Redis streams.

KVStore

The main store struct that manages all data and server operations.
Info
Info
Server configuration and replication information
store
map[string]string
default:"{}"
Internal key-value storage map
expiryMap
map[string]chan int
default:"{}"
Manages key expiration channels
AckCh
chan int
Channel for replication acknowledgments
ProcessedWrite
bool
Tracks if write operations have been processed
StreamXCh
chan []byte
Channel for stream entry notifications
Stream
map[string][]StreamEntry
default:"{}"
Storage for Redis stream entries by stream key

New

Creates a new KVStore instance with default configuration.
func New() *KVStore
return
*KVStore
A new KVStore instance configured as master on port 6379
Example:
kvStore := store.New()

Set

Stores a key-value pair with optional expiration.
func (kv *KVStore) Set(key, value string, expiry int)
key
string
required
The key to store
value
string
required
The value to store
expiry
int
default:"-1"
Expiration time in milliseconds. Use -1 for no expiration
Example:
// Set without expiration
kvStore.Set("user:1", "John Doe", -1)

// Set with 5 second expiration
kvStore.Set("session:abc", "active", 5000)

HandleConnection

Handles incoming client connections and processes commands.
func (kv *KVStore) HandleConnection(connection Connection, parser *resp.Parser)
connection
Connection
required
The connection wrapper containing the net.Conn and transaction state
parser
*resp.Parser
required
RESP protocol parser for reading commands
Example:
conn, _ := listener.Accept()
connection := store.Connection{
    Conn:       conn,
    TxnStarted: false,
    TxnQueue:   [][]string{},
}
parser := resp.NewParser(conn)
go kvStore.HandleConnection(connection, parser)

processCommand

Processes individual Redis commands and returns the response.
func (kv *KVStore) processCommand(buff []string, connection *Connection) []byte
buff
[]string
required
Array of command and arguments
connection
*Connection
required
Pointer to the connection for transaction state management
return
[]byte
RESP-encoded response to send to the client
Supported Commands:
  • PING, ECHO - Basic protocol commands
  • SET, GET, DEL - Key-value operations
  • INCR - Atomic increment
  • KEYS, TYPE - Key introspection
  • CONFIG, INFO - Server information
  • XADD, XRANGE, XREAD - Stream operations
  • MULTI, EXEC, DISCARD - Transactions
  • REPLCONF, PSYNC, WAIT - Replication

LoadFromRDB

Loads key-value pairs and expiration data from an RDB snapshot.
func (kv *KVStore) LoadFromRDB(rdb *rdb.RDB)
rdb
*rdb.RDB
required
Parsed RDB file structure
Example:
rdbFile, _ := rdb.NewRDB("/var/lib/redis/dump.rdb")
rdbFile.Parse()
kvStore.LoadFromRDB(rdbFile)

HandleReplication

Establishes replication connection to a master server.
func (kv *KVStore) HandleReplication()
This method performs the replication handshake and starts listening for commands from the master. Example:
if kvStore.Info.Role == "slave" {
    kvStore.HandleReplication()
}

Connection

Wraps a network connection with transaction state.
Conn
net.Conn
The underlying network connection
TxnStarted
bool
default:"false"
Whether a MULTI transaction has been started
TxnQueue
[][]string
default:"[]"
Queue of commands to execute on EXEC

Info

Server configuration and replication metadata.
Role
string
default:"master"
Server role: “master” or “slave”
MasterIP
string
IP address of the master (slave only)
MasterPort
string
Port of the master (slave only)
MasterReplId
string
Master replication ID
MasterReplOffSet
int
default:"0"
Current replication offset
MasterConn
net.Conn
Connection to master server (slave only)
slaves
[]net.Conn
Connected slave connections (master only)
Port
string
default:"6379"
Server listening port
flags
map[string]string
Command-line configuration flags

StreamEntry

Represents a single entry in a Redis stream.
Id
string
Stream entry ID in format “timestamp-sequence”
Pair
map[string]string
Field-value pairs for this stream entry
Example:
entry := StreamEntry{
    Id: "1234567890-0",
    Pair: map[string]string{
        "temperature": "72.5",
        "humidity": "45",
    },
}

Complete Example

Here’s how the store package integrates with other components:
package main

import (
    "fmt"
    "net"
    "github.com/codecrafters-io/redis-starter-go/app/resp"
    "github.com/codecrafters-io/redis-starter-go/app/store"
)

func main() {
    // Initialize store
    kvStore := store.New()
    kvStore.ParseCommandLine()
    
    // Handle replication if configured as slave
    if kvStore.Info.Role == "slave" {
        kvStore.HandleReplication()
    }
    
    // Start listening
    addr := fmt.Sprintf("0.0.0.0:%s", kvStore.Info.Port)
    listener, _ := net.Listen("tcp", addr)
    defer listener.Close()
    
    // Accept connections
    for {
        conn, _ := listener.Accept()
        connection := store.Connection{
            Conn:       conn,
            TxnStarted: false,
            TxnQueue:   [][]string{},
        }
        parser := resp.NewParser(conn)
        go kvStore.HandleConnection(connection, parser)
    }
}

Build docs developers (and LLMs) love