Design a service to expose a local web server (localhost:8080) to the public internet (myapp.tunnel.com).
Bypass NAT/Firewalls without manual port forwarding.
1. Who are the actors?
Agent (Client): Runs on developer's machine.
Tunnel Server: Runs in the cloud, accepts public traffic.
Public User: Accesses the public URL.
2. What are the must-have features? (Core)
Reverse Tunneling: Agent initiates connection to Server (Outbound allowed).
Public Endpoint: Values like *.tunnel.com map to specific Agents.
Traffic Forwarding: HTTP requests on Cloud are forwarded to Localhost.
3. What are the constraints?
Latency: Minimal overhead.
Connection: Must be persistent (TCP/WebSocket).
Phase 2: Use Cases
UC1: Agent Connects
Actor: Agent Flow:
Agent starts: ngrok http 8080.
Agent connects to Tunnel Server via TCP (Port 4443).
Server assigns subdomain ran-dom.tunnel.com.
Connection remains open (Heartbeats).
UC2: Public Request
Actor: Public User Flow:
User hits ran-dom.tunnel.com.
Tunnel Server identifies the active Socket Connection for ran-dom.
Server writes raw request bytes to the Socket.
Agent reads bytes, opens connection to localhost:8080.
Agent proxies request/response.
Phase 3: Class Diagram
Step 1: Core Entities
TunnelServer: Manages registry of active tunnels.
Agent: The local process.
Connection: Wrapper around the persistent TCP socket.
TunnelSession: State of a specific tunnel.
UML Diagram
Phase 4: Design Patterns
1. Reverse Proxy Pattern
Description: A server that sits between client devices and a web server, forwarding client requests to the web server and returning the server's responses.
Why used: The Tunnel Server acts as a gateway (Reverse Proxy), accepting public traffic on tunnel.com and forwarding it to the hidden Agent. It masks the identity and location of the origin server (localhost).
2. Multiplexing (IO Pattern)
Description: Transmitting multiple signals or streams of information over a single communication channel.
Why used: To prevent "Head-of-Line Blocking" and resource exhaustion, we send multiple HTTP requests over a single TCP connection between Agent and Server. This requires independent frames/streams.
Phase 5: Code Key Methods
Java Implementation
Phase 6: Discussion
NAT Traversal
Q: "Why does this work behind Firewalls?"
A: "Firewalls typically block Inbound connections but allow Outbound connections (HTTP/TCP). The Agent initiates the Outbound connection. Once established, the socket is bidirectional."
Multiplexing
Q: "Problem with simple TCP forwarding?"
A: "Head-of-Line Blocking. If one request takes 10s, the pipe is blocked.
Solution: Break data into Frames [StreamID][Length][Data].
Server sends Stream 1 frame, then Stream 2 frame.
Agent reassembles frames by ID. Allows concurrent requests on one socket."
Security
Q: "How to secure the tunnel?"
A: "Mutual TLS (mTLS). Agent and Server authenticate each other with certificates. Traffic inside the tunnel is encrypted. Also, implement Rate Limiting per tunnel."