← Amazon

Amazon CodingFree previewFree

Consistent Hashing Packet Router

Last asked

phoneSWE
consistent hashingbinary searchhashing

Problem

Route each packet identifier to one of the active backend servers so the same identifier always maps to the same server, and so adding or removing a server moves as few identifiers as possible.

Part 1 — Stable mapping: given the list of active server IDs and a packet identifier (for example a source IP address and port), return the server that handles the packet. With an unchanged server set, the same identifier must always map to the same server.

Part 2 — Dynamic servers: servers can be added or removed at any time. Adding server4 should let it receive traffic while keeping as many existing assignments as possible; removing server3 should spread its traffic over the remaining servers while disturbing other assignments as little as possible.

Starter code

class PacketRouter:
    def __init__(self, servers: list[str]) -> None:
        ...

    def route(self, packet_id: str) -> str:
        # server that handles packet_id; stable while the server set is unchanged
        ...

    def add_server(self, server_id: str) -> None:
        ...

    def remove_server(self, server_id: str) -> None:
        ...

Input

The list of active server IDs and a packet identifier string such as "192.168.1.1:8080"; later, server additions and removals.

Output

The ID of the server that should handle the packet.

Constraints

  • A hash function may be assumed to be available.

Examples

Example 1

Input

servers = ["server1", "server2", "server3"] route("192.168.1.1:8080") route("10.0.0.5:8080") route("192.168.1.1:8080")

Output

"server3", "server1", "server3"

Explanation

The interviewer's example: the same identifier returns the same server every time.

Follow-ups

  • With more time, what would you improve? The candidate proposed binary search for the server lookup.