Skip to content

Inengs/redis-server-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

Miniature Redis server

This is for me to learn concepts like TCP, RESP and understand redis better. I used the blog Write your own miniature Redis with Python on charlesleifer.com

Uses RESP Protocol (Redis Serialization protocol)

Data Type Prefix Structure Example
Simple String + +{string data}\r\n +this is a simple string\r\n
Error - -{error message}\r\n -ERR unknown command "FLUHS"\r\n
Integer : :{the number}\r\n :1337\r\n
Binary $ ${number of bytes}\r\n{data}\r\n $6\r\nfoobar\r\n
Array * *{number of elements}\r\n{0 or more of above}\r\n *3\r\n+a simple string element\r\n:12345\r\n$7\r\ntesting\r\n
Dictionary % %{number of keys}\r\n{0 or more of above}\r\n %3\r\n+key1\r\n+value1\r\n+key2\r\n*2\r\n+value2-0\r\n+value2-1\r\n:3\r\n$7\r\ntesting\r\n
NULL $ $-1\r\n (string of length -1) $-1\r\n

TCP

Client → SYN → Server ("I want to connect") - SYN = Synchronize Client ← SYN-ACK ← Server ("OK, I acknowledge") - SYN-ACK = SYN(its own sequence number), ACK (acknowledges client’s number) Client → ACK → Server ("Great, we're connected") - ACK confirming server’s sequence number

gevent

Normally each connection would need its own thread. Gevent uses green threads (lightweight coroutines) instead, so 64 clients can be handled concurrently without the overhead of 64 real OS threads.

socket

A socket is basically just a door that lets two programs talk to each other over a network AF_INET just means "use the internet (IPv4)" SOCK_STREAM means "keep the line open continuously" (as opposed to sending one-off messages)

Without sockets, two programs have no way of talking to each other at all. It's the most fundamental building block of all network communication

Run

  • terminal 1 python skeleton.py

  • terminal 2 python

interact with the server:

from skeleton import Client

c = Client()

c.set('name', 'Alice')       # returns 1
c.get('name')                # returns 'Alice'
c.delete('name')             # returns 1
c.get('name')                # returns None

c.mset('a', '1', 'b', '2')  # set multiple keys at once
c.mget('a', 'b')             # returns ['1', '2']

c.flush()                    # clears all keys, returns count of deleted keys

About

Lightweight Redis-like in-memory key-value store with GET/SET, MGET/MSET, and FLUSH commands. Built in Python using gevent with RESP protocol support and concurrent TCP server handling.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages