HTTP Server and Request Routing

Code for this post lives on the shreder branch.

HTTP Server and Request Routing

The server handles HTTP requests and routes them to the appropriate nodes based on the hash ring.

Implementation

// shreder/server.go
type CacheServer struct {
cache *Cache
peers []string
mu sync.Mutex
selfID string
hashRing *hash_ring.HashRing
}
func (cs *CacheServer) SetHandler(w http.ResponseWriter, r *http.Request) {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var request setRequest
if err := json.Unmarshal(bodyBytes, &request); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
isReplication := r.Header.Get(replicationHeader) == "true"
targetNode := cs.hashRing.GetNode(request.Key)
if targetNode.Address == cs.selfID {
cs.cache.Set(request.Key, request.Value, 10*time.Minute)
if !isReplication {
cs.replicaset(request.Key, request.Value)
}
w.WriteHeader(http.StatusOK)
} else {
r.Body = io.NopCloser(bytes.NewReader(bodyBytes))
cs.forwardRequest(targetNode, r, w)
}
}

Request Flow

  1. Client sends request to any node
  2. Node uses hash ring to determine responsible node
  3. If current node is responsible, it processes the request locally
  4. Otherwise, it forwards the request to the responsible node
  5. Data changes are replicated to peer nodes
Code for this post lives on the shreder branch.

© 2026 Byron Mahinya