TASK
Implementation
Build an HTTP-aware (Layer 7) load balancer:
- Parse HTTP request (method, path, headers)
- Route based on Host header (virtual hosts)
- Route based on URL path (/api/* -> api-servers)
- Implement session stickiness via cookie
- Support URL rewriting
Layer 7 enables intelligent routing based on request content.
Sample Test Cases
Path-based routingTimeout: 5000ms
Input
{"src":"c0","dest":"lb","body":{"type":"init","msg_id":1,"node_id":"lb","node_ids":["lb","s1","s2","s3"]}}
{"src":"client","dest":"lb","body":{"type":"http_request","msg_id":2,"path":"/api/users","method":"GET"}}
Expected Output
{"src":"lb","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}
{"src":"lb","dest":"client","body":{"type":"http_response","in_reply_to":2,"msg_id":1,"path":"/api/users","routed_to":"s1","status":200}}
Hints
Hint 1▾
Parse HTTP headers
Hint 2▾
Route based on path or host
Hint 3▾
Support session stickiness
OVERVIEW
Theoretical Hub
Layer 4 vs Layer 7
Layer 4 LBs see only TCP/UDP - fast but limited. Layer 7 LBs understand HTTP - can route by URL, read cookies, modify headers. More powerful but higher overhead.
Session Stickiness
Some apps require all requests from a user to reach the same server (sessions). The LB can track sessions via cookies or source IP. Trade-off: stickiness can cause uneven load.
Key Concepts
Layer 7HTTP routingcontent-based
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python3
import sys
import json
import re
class Layer7LB:
def __init__(self):
self.routes = [] # (pattern, servers)
self.sessions = {} # session_id -> server
self.default_servers = []
def add_route(self, path_pattern, servers):
# TODO: Add routing rule
pass
def match_route(self, path):
# TODO: Find servers matching path
pass
def get_session_server(self, session_id, servers):
# TODO: Sticky session handling
pass
def route_request(self, request):
# TODO: Parse request, select server
pass
if __name__ == "__main__":
pass