A reverse proxy can route requests by virtual host and path while removing unhealthy destinations from consideration.
Design a ReverseProxyRouter class:
ReverseProxyRouter(String[] hostPatterns, String[] pathPrefixes, String[] backends) stores aligned route rules. Every backend starts healthy.void setHealthy(String backend, boolean healthy) changes health for every rule using that backend.String route(String host, String path) returns the best healthy backend or "NO_BACKEND".
Host precedence is exact host, then wildcard suffix such as *.example.com, then catch-all *. Host comparisons are case-insensitive. A wildcard requires at least one label before its suffix, so *.example.com matches a.example.com and a.b.example.com, but not example.com.
Within the best matching host rank, longest path prefix wins. / matches every path. Any other prefix matches an identical path or a descendant separated by /; /api does not match /apix. Exact ties use the first input rule.
Example 1:
Input:
Output:
Explanation: The exact API host wins for the first request. The marketplace subdomain matches the wildcard, and the unrelated domain reaches the catch-all rule.
Example 2:
Input:
Output:
Explanation: Unhealthy rules are excluded before precedence is evaluated, so routing falls back to the next-best healthy rule.
Constraints
0 <= hostPatterns.length == pathPrefixes.length == backends.length <= 10^5- A host pattern is
*, an exact ASCII hostname, or *. followed by a hostname suffix. - Every path and path prefix starts with
/ and excludes query strings. - A non-root path prefix does not end with
/. - Hosts are compared case-insensitively; paths are case-sensitive.
setHealthy names a backend present in the constructor."NO_BACKEND" is not a backend name.- At most
10^4 total method calls are made.