Top Five Client IPv4s Across Server Logs

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given server log lines collected across one or more log files, identify up to five client IPv4 addresses responsible for the highest number of completed HTTP requests. Diagnostic entries, background worker notices, and lines that merely mention an IP address without logging a finished HTTP request must be excluded.

Implement top_request_ips(files: List[List[str]]) -> List[List[str]], where files[i] contains the lines from the i-th log file. Return a list of [ip, count] pairs (at most five), with count formatted as a base-10 string:

  1. Order results by numeric request count descending ("12" comes before "9").
  2. Break ties by numeric IPv4 address ascending, comparing the four integer octets from left to right ("9.255.255.255" comes before "10.0.0.1", and "198.51.100.7" comes before "198.51.100.102").
  3. If fewer than five distinct client IPv4 addresses appear in completed request records, return only those addresses ([] if none).

A single log line counts as one completed HTTP request if and only if it contains both of the following segments in left-to-right order on that same line:

  • HTTP request segment (METHOD URL HTTP/version):
    • METHOD begins at a word boundary (not attached to preceding word characters, so "FORGET" does not match "GET") and is one of GET, POST, PUT, PATCH, DELETE, HEAD, or OPTIONS.
    • URL is a non-empty token containing no whitespace characters, separated from METHOD and HTTP/version by single spaces.
    • version is 1.0, 1.1, or 2.0, and is not immediately followed by another ASCII digit.
  • Client and status segment (from A.B.C.D:port - status) appearing after the request segment:
    • A.B.C.D consists of four ASCII decimal octets, each in 0..255, with no leading zeros on multi-digit octets (0 is valid; 01 is invalid).
    • port is an ASCII decimal integer in 1..65535.
    • status is an HTTP response status of exactly three ASCII digits (not immediately followed by a fourth ASCII digit).

Quote characters on a line may be escaped with backslashes (\"), and extra metadata tokens may appear between HTTP/version and from ..., so match the request and client segments directly rather than splitting on quotes. Group strictly by the IPv4 address (ignoring client ports), count every completed request regardless of HTTP status code (2xx, 3xx, 4xx, 5xx) or private IP range, and do not deduplicate identical lines within or across files.

Examples

Example 1

files = [
    [
        'ts="08:15:01Z" event="POST https://edge.service.internal/v1/login HTTP/2.0 from 198.51.100.14:52310 - 200 128B"',
        'ts="08:15:02Z" event="tls_handshake_retry" Client IP="198.51.100.99:44100"',
        'ts="08:15:03Z" event="DELETE https://edge.service.internal/v1/session HTTP/1.1 from 198.51.100.14:52311 - 503 0B"',
    ],
    [
        'ts="08:15:04Z" event="GET https://edge.service.internal/healthz HTTP/1.1 from 198.51.100.7:60120 - 200 2B"',
        'ts="08:15:05Z" event="worker_queue_idle"',
        'ts="08:15:06Z" event="PUT https://edge.service.internal/v1/items HTTP/2.0 from 198.51.100.102:49001 - 404 19B"',
    ],
]
# Output: [["198.51.100.14", "2"], ["198.51.100.7", "1"], ["198.51.100.102", "1"]]

Walk-through: 198.51.100.14 completes two requests across ports 52310 (200) and 52311 (503). The Client IP="198.51.100.99:44100" handshake retry and "worker_queue_idle" line have no METHOD URL HTTP/version segment and are ignored. 198.51.100.7 and 198.51.100.102 tie at 1 request each; numeric octet order places 7 ahead of 102.

Example 2

files = [
    [
        r'ts=\"09:00:00Z\" msg=\"GET /metrics HTTP/1.0 trace=ab1 from 203.0.113.20:8080 - 200 64B\"',
        r'ts=\"09:00:01Z\" msg=\"GET /metrics HTTP/1.0 trace=ab2 from 203.0.113.20:8081 - 200 64B\"',
        r'ts=\"09:00:02Z\" msg=\"HEAD /ping HTTP/1.1 from 192.0.2.250:443 - 204 0B\"',
        r'ts=\"09:00:03Z\" msg=\"OPTIONS /cors HTTP/2.0 from 203.0.113.5:443 - 200 0B\"',
        r'ts=\"09:00:04Z\" msg=\"PATCH /cfg HTTP/1.1 from 203.0.113.9:443 - 200 12B\"',
        r'ts=\"09:00:05Z\" msg=\"POST /hook HTTP/1.1 from 203.0.113.40:443 - 500 0B\"',
        r'ts=\"09:00:06Z\" msg=\"GET /slow HTTP/1.1 from 203.0.113.100:443 - 504 0B\"',
    ]
]
# Output: [
#     ["203.0.113.20", "2"],
#     ["192.0.2.250", "1"],
#     ["203.0.113.5", "1"],
#     ["203.0.113.9", "1"],
#     ["203.0.113.40", "1"],
# ]

Walk-through: Escaped quotes (\") and extra fields (trace=ab1) do not prevent matching. Six distinct IPv4 addresses appear: 203.0.113.20 leads with "2", while the five addresses tied at "1" are ordered by numeric octets (192.0.2.250 first because 192 < 203, then fourth octets 5 < 9 < 40 < 100), dropping 6th-place 203.0.113.100.

Constraints

  • 0 <= len(files) <= 20
  • Total lines across all files: at most 200,000; total characters across all lines: at most 20,000,000.
  • Each counted line contains one valid HTTP request/client pair; IPv6 addresses, proxy forwarding headers, and multi-line log entries are outside scope.
  • Only ASCII digits 0-9 are valid in IPv4 octets, port numbers, HTTP versions, and status codes.

Step-by-step walkthrough

  1. Understand what counts as a completed request

    We receive files, a list of server log files where each inner list holds the lines of one file. We need to return up to five [ip, count] pairs (with count formatted as a base-10 string), sorted by:

    1. Request count descending as integers (12 comes before 9).
    2. Numeric IPv4 address ascending on ties (198.51.100.7 comes before 198.51.100.102).

    The main pitfall is that IPv4 addresses appear in diagnostic and background entries that are not completed HTTP requests:

    event="POST https://edge.service.internal/v1/login HTTP/2.0 from 198.51.100.14:52310 - 200 128B"
           |------------------ 1. request portion -----------------||----- 2. client & status ----|
           -> COUNT 198.51.100.14
    
    event="tls_handshake_retry" Client IP="198.51.100.99:44100"           -> IGNORE (diagnostic)
    event="upstream from 198.51.100.99:44100 - 200 before GET /x HTTP/1.1" -> IGNORE (wrong order)
    event="worker_queue_idle"                                             -> IGNORE (background)
    

    A line counts once if and only if it contains both segments in left-to-right order:

    • Request portion: METHOD URL HTTP/version (METHOD in GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS; version in 1.0, 1.1, 2.0).
    • Client portion later on the same line: from A.B.C.D:port - status (A..D in 0..255 with no leading zeros on multi-digit octets, port in 1..65535, status of exactly 3 ASCII digits).

    Notice why naive shortcuts fail: grabbing every IPv4-shaped substring falsely counts Client IP= lines, and splitting on " breaks whenever log lines contain backslash-escaped quotes (\"). With at most 200,000 lines and 20,000,000 characters total, scanning each line once and sorting the distinct client IPs runs in milliseconds.

  2. Match the request and client fields in order

    We can locate both segments cleanly using two regular expressions (text-matching patterns), independent of quote positions or intermediate metadata fields:

    • \b (a word boundary) before the HTTP method prevents matching "GET" inside "FORGET".
    • \S+ matches the URL as one continuous run of non-whitespace characters.
    • [0-9] is used instead of \d because Python's \d also matches Unicode digits from non-ASCII scripts (such as Arabic-Indic "٣"), which int() would otherwise accept.
    • (?![0-9]) (a negative lookahead meaning "not immediately followed by another ASCII digit") rejects "HTTP/1.10" and 4-digit numbers like "- 2000".
    import re
    
    # Phase 1a — Match the HTTP request portion: "METHOD URL HTTP/version".
    REQUEST_RE = re.compile(
        r"\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) \S+ HTTP/(?:1\.0|1\.1|2\.0)(?![0-9])"
    )
    
    # Phase 1b — Match the client/status suffix: " from A.B.C.D:port - status".
    CLIENT_RE = re.compile(
        r" from ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}):([0-9]{1,5}) - [0-9]{3}(?![0-9])"
    )
    
  3. Validate IPv4 octets, ports, and numeric tie-breaking

    An IPv4 address like "198.51.100.14" consists of four octets — the four decimal integers separated by dots, each representing one 8-bit byte in 0..255. Because CLIENT_RE only checks that each group has 1 to 3 digits, it will initially match out-of-range octets like "256.1.1.1" or leading-zero octets like "10.0.0.01" as well as ports like 0 or 65536.

    We write a helper ipv4_octets(ip) that validates each octet (0..255, no leading zero when len(part) > 1) and returns a 4-int tuple (A, B, C, D). That exact tuple also handles tie-breaking! Compare alphabetical (lexicographical) string sorting against numeric tuple sorting:

    String comparison:  "198.51.100.102" < "198.51.100.7"      ('1' < '7' after last dot — WRONG!)
    Tuple comparison:   (198, 51, 100, 7) < (198, 51, 100, 102) (7 < 102 in 4th octet — RIGHT!)
    

    In client_ip(line), we search for CLIENT_RE starting at request.end() (right after the earliest valid request match, preserving the widest suffix of the line). And we iterate with finditer rather than stopping at the first .search() hit: if a line has an invalid decoy like from 256.1.1.1:80 - 200 ahead of a real from 1.2.3.4:80 - 200, skipping the invalid decoy still finds the valid client segment.

    from typing import Optional, Tuple
    
    
    def ipv4_octets(ip: str) -> Optional[Tuple[int, ...]]:
        """Convert 'A.B.C.D' into a 4-int tuple (A, B, C, D), or None if invalid."""
        octets = []
        for part in ip.split("."):
            # Multi-digit octets may not start with "0" ("0" is valid, "01" is not).
            if len(part) > 1 and part[0] == "0":
                return None
            value = int(part)
            if value > 255:
                return None
            octets.append(value)
        return tuple(octets)
    
    
    def client_ip(line: str) -> Optional[str]:
        """Return the client IPv4 string of a completed request line, or None otherwise."""
        request = REQUEST_RE.search(line)
        if request is None:
            return None
    
        for client in CLIENT_RE.finditer(line, request.end()):
            ip = client.group(1)
            port = int(client.group(2))
            if ipv4_octets(ip) is not None and 1 <= port <= 65535:
                return ip
        return None
    
  4. Aggregate counts and rank the top five

    Now we sweep every line across every file and accumulate completed request totals in counts[ip]. Because leading zeros are disallowed, every valid IPv4 address has a unique string representation, making ip an unambiguous dictionary key. Client ports are ignored, non-2xx statuses (404, 503) still count, and repeated lines across files are tallied every time.

    To sort by count descending and numeric IPv4 ascending in one .sort() call, we construct tuples (-count, octets, ip):

    • Negating count places larger counts first (-12 < -9).
    • When counts tie, Python compares the second tuple item octets ((198, 51, 100, 7) < (198, 51, 100, 102)).
    from typing import Dict, List
    
    
    def top_request_ips(files: List[List[str]]) -> List[List[str]]:
        """Return up to 5 busiest client IPs as [ip, decimal_count_str] rows."""
        counts: Dict[str, int] = {}
        for lines in files:
            for line in lines:
                ip = client_ip(line)
                if ip is not None:
                    counts[ip] = counts.get(ip, 0) + 1
    
        ranked = []
        for ip, count in counts.items():
            octets = ipv4_octets(ip)
            if octets is not None:
                ranked.append((-count, octets, ip))
        ranked.sort()
    
        result = []
        for negative_count, _octets, ip in ranked[:5]:
            positive_count = -negative_count
            result.append([ip, str(positive_count)])
        return result
    
  5. Trace through Example 1 step by step

    Walk through the two files from Example 1 line by line:

    File / Line  Log text (shortened)                                      Extracted IP       counts
    -----------  --------------------------------------------------------  -----------------  --------------------------------
    F1, line 1   POST .../v1/login HTTP/2.0 from 198.51.100.14:52310 - 200 "198.51.100.14"    {".14": 1}
    F1, line 2   event="tls_handshake_retry" Client IP="198.51.100.99..."  None               {".14": 1}
    F1, line 3   DELETE .../session HTTP/1.1 from 198.51.100.14:52311 - 503 "198.51.100.14"   {".14": 2}
    F2, line 1   GET .../healthz HTTP/1.1 from 198.51.100.7:60120 - 200    "198.51.100.7"     {".14": 2, ".7": 1}
    F2, line 2   event="worker_queue_idle"                                 None               {".14": 2, ".7": 1}
    F2, line 3   PUT .../v1/items HTTP/2.0 from 198.51.100.102:49001 - 404 "198.51.100.102"   {".14": 2, ".7": 1, ".102": 1}
    
    Sort keys:   [(-2, (198, 51, 100, 14),  "198.51.100.14"),
                  (-1, (198, 51, 100, 7),   "198.51.100.7"),
                  (-1, (198, 51, 100, 102), "198.51.100.102")]
    
    Output:      [["198.51.100.14", "2"], ["198.51.100.7", "1"], ["198.51.100.102", "1"]]
    

    Notice that 198.51.100.99 never enters counts (it only appeared in a TLS retry diagnostic), 198.51.100.14 merges ports 52310 and 52311 including a 503 response into "2", and numeric octet tie-breaking orders .7 ahead of .102.

  6. Stream compressed archives and interpret traffic volume safely

    When inspecting multi-gigabyte .tar.gz log bundles on disk, loading every file into RAM at once will exhaust memory. Instead, stream the archive line by line (tarfile.open(archive_path, mode="r|gz"), where | reads sequentially without seeking backward), updating only counts so memory stays O(D) for D distinct client IPv4s:

    import tarfile
    from typing import Dict, Iterator
    
    
    def iter_archive_lines(archive_path: str) -> Iterator[str]:
        """Stream lines one by one from every regular file inside a .tar.gz archive."""
        with tarfile.open(archive_path, mode="r|gz") as archive:
            for member in archive:
                if not member.isfile():
                    continue
                byte_stream = archive.extractfile(member)
                if byte_stream is None:
                    continue
                for raw_line in byte_stream:
                    # errors="replace" prevents one corrupted non-UTF-8 byte from aborting the scan
                    yield raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
    
    
    def count_archive_ips(archive_path: str) -> Dict[str, int]:
        counts: Dict[str, int] = {}
        for line in iter_archive_lines(archive_path):
            ip = client_ip(line)
            if ip is not None:
                counts[ip] = counts.get(ip, 0) + 1
        return counts
    

    Equally important during an incident: high request volume alone does not prove an IP is malicious. Corporate/campus NAT gateways, mobile Carrier-Grade NAT, reverse proxies or load balancers (when logging peer sockets rather than verified client-IP headers), and authorized health checks or partner webhooks all concentrate heavy legitimate traffic behind single IPv4 addresses. Corroborate volume against sudden rate spikes over baseline, error/auth failure ratios (401/403/404 bursts), endpoint targeting, and ASN ownership before applying rate limits or blocks.

  7. Put the complete solution together

    Here is the complete, self-contained implementation matching every rule and edge case.

    from typing import Dict, List, Optional, Tuple
    import re
    
    # Phase 1a — Match the HTTP request portion: "METHOD URL HTTP/version".
    # \b ensures METHOD starts a new word (so "FORGET" does not match as "GET").
    # \S+ matches the non-whitespace URL without relying on quote positions.
    # (?![0-9]) prevents matching longer versions such as "HTTP/1.10".
    REQUEST_RE = re.compile(
        r"\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) \S+ HTTP/(?:1\.0|1\.1|2\.0)(?![0-9])"
    )
    
    # Phase 1b — Match the client/status suffix: " from A.B.C.D:port - status".
    # Use [0-9] rather than \d because Python's \d also matches non-ASCII digits like "٣".
    # (?![0-9]) ensures the HTTP status has at most (and therefore exactly) 3 digits.
    CLIENT_RE = re.compile(
        r" from ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}):([0-9]{1,5}) - [0-9]{3}(?![0-9])"
    )
    
    
    def ipv4_octets(ip: str) -> Optional[Tuple[int, ...]]:
        """Convert 'A.B.C.D' into a 4-int tuple (A, B, C, D), or None if invalid."""
        # octets: accumulates the 4 numeric parts, e.g. [198, 51, 100, 14] for "198.51.100.14"
        octets = []
        for part in ip.split("."):
            # Multi-digit octets may not start with "0" ("0" is valid, "01" is not).
            if len(part) > 1 and part[0] == "0":
                return None
            value = int(part)
            if value > 255:
                return None
            octets.append(value)
        return tuple(octets)
    
    
    def client_ip(line: str) -> Optional[str]:
        """Return the client IPv4 string of a completed request line, or None otherwise."""
        request = REQUEST_RE.search(line)
        if request is None:
            return None
    
        # The client field must appear AFTER the request portion. Starting at request.end()
        # after the earliest request match covers the widest possible suffix of the line.
        # We iterate with finditer so an invalid decoy like "from 256.1.1.1:80 - 200"
        # does not hide a real valid client field later on the same line.
        for client in CLIENT_RE.finditer(line, request.end()):
            ip = client.group(1)
            port = int(client.group(2))
            if ipv4_octets(ip) is not None and 1 <= port <= 65535:
                return ip
        return None
    
    
    def top_request_ips(files: List[List[str]]) -> List[List[str]]:
        """Return up to 5 busiest client IPs as [ip, decimal_count_str] rows."""
        # Phase 2 — Count completed requests across all files (ports ignored, no deduplication).
        # counts: maps IPv4 string -> total completed requests, e.g. {"198.51.100.14": 2}
        counts: Dict[str, int] = {}
        for lines in files:
            for line in lines:
                ip = client_ip(line)
                if ip is not None:
                    counts[ip] = counts.get(ip, 0) + 1
    
        # Phase 3 — Sort by count descending (-count ascending), then numeric IPv4 octets ascending.
        # ranked: list of (-count, (A, B, C, D), ip_str), e.g. [(-2, (198, 51, 100, 14), "198.51.100.14")]
        ranked = []
        for ip, count in counts.items():
            octets = ipv4_octets(ip)
            if octets is not None:
                ranked.append((-count, octets, ip))
        ranked.sort()
    
        # Phase 4 — Take at most 5 winners and format counts back as decimal strings.
        result = []
        for negative_count, _octets, ip in ranked[:5]:
            positive_count = -negative_count
            result.append([ip, str(positive_count)])
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine reading a coffee shop's paper register tape during a rush to find which five loyalty-card numbers placed the most finished orders. Some lines on the tape are real completed receipts (drink + customer ID + final total), while other lines are printer notes that merely mention an ID ("reprinting cup label for customer 99"). If you tally every customer number printed anywhere on the tape, you accidentally count diagnostic notes as extra orders.

Server log aggregation works the exact same way. A naive approach that grabs every IPv4-shaped substring falsely counts Client IP= handshake diagnostics, splitting on " breaks whenever a log message contains backslash-escaped quotes (\"), and sorting counts or IP strings in lexicographical order (character-by-character dictionary order) puts "9" ahead of "12" and "198.51.100.102" ahead of "198.51.100.7". Instead, we use two targeted regular expressions (text-matching patterns) — first finding METHOD URL HTTP/version and then searching after it for a valid from A.B.C.D:port - status — accumulate totals in a dictionary, and sort using numeric tuples (-count, (A, B, C, D)) where (A, B, C, D) are the four integer octets (0..255 numbers between the dots of an IPv4 address).

Walk through five sample lines from Example 1: 1. POST .../v1/login HTTP/2.0 from 198.51.100.14:52310 - 200 -> valid request + client suffix -> counts["198.51.100.14"] = 1. 2. event="tls_handshake_retry" Client IP="198.51.100.99:44100" -> no METHOD URL HTTP/version -> ignored. 3. DELETE .../v1/session HTTP/1.1 from 198.51.100.14:52311 - 503 -> valid (503 counts, port 52311 ignored) -> counts["198.51.100.14"] = 2. 4. GET .../healthz HTTP/1.1 from 198.51.100.7:60120 - 200 -> valid -> counts["198.51.100.7"] = 1. 5. PUT .../v1/items HTTP/2.0 from 198.51.100.102:49001 - 404 -> valid -> counts["198.51.100.102"] = 1. Sorting (-count, octets, ip) places 198.51.100.14 ("2") first, then breaks the "1" tie numerically (7 < 102) to return [["198.51.100.14", "2"], ["198.51.100.7", "1"], ["198.51.100.102", "1"]].

Complexity

  • Time: O(L + D log D), where L is the total number of characters across all log lines and D is the number of distinct valid client IPv4 addresses (D is at most the number of lines, up to 200,000). We scan each line left-to-right with two non-backtracking patterns (\S+ stops at the next space) and do an O(1) dictionary update per valid line, costing O(L) total; then we sort D fixed-size 4-octet tuples in O(D log D) time.
  • Space: O(D) auxiliary memory beyond the input files list, because counts and ranked store at most one entry per distinct client IPv4 address. When streaming a compressed archive line by line from disk, total RAM stays O(D) plus a single line buffer regardless of archive size.

Edge cases

  • Empty input ([] or [[], []]): Returns [] cleanly.
  • Fewer than five distinct client IPs: Returns only the addresses seen (never pads with dummy rows).
  • Equal request counts: Broken by numeric octets left to right, so 9.255.255.255 comes before 10.0.0.0 and 198.51.100.7 comes before 198.51.100.102.
  • Same IP across different ports or multiple files: Grouped under one IP key; exact duplicate lines are counted every time (no file-overlap deduplication).
  • Error HTTP statuses and boundary values: 404 and 503 responses, private ranges (10.x.x.x, 192.168.x.x), 0.0.0.0, 255.255.255.255, port 1, and port 65535 all count.
  • Wrong field order on a line: upstream from 198.51.100.99:44100 - 200 before GET /x HTTP/1.1 has from before the HTTP request, so searching after request.end() properly ignores it.
  • Invalid decoy from before a valid from: On GET /a HTTP/1.1 from 256.1.1.1:80 - 200 from 1.2.3.4:80 - 200, 256.1.1.1 fails octet validation (256 > 255), and finditer continues to find and count 1.2.3.4.

Common mistakes

  • Matching every IPv4-shaped string on every line. That falsely counts Client IP= handshake diagnostics and socket-reset messages as extra HTTP requests.
  • Splitting lines on " and indexing a fixed slot. Backslash-escaped quotes (\") inside log messages shift split indices and break positional parsing.
  • Comparing IP addresses or counts as strings. Alphabetically, "9" > "12" and "198.51.100.102" < "198.51.100.7"; always keep counts as integers and IPs as 4-int tuples until formatting the final 5 rows.
  • Forgetting boundaries around methods, versions, or statuses. Without \b and (?![0-9]), "FORGET" matches "GET", "HTTP/1.10" matches "HTTP/1.1", and "- 2000" matches "- 200".
  • Stopping after the first regex hit of CLIENT_RE with .search(). If an earlier " from 256.1.1.1:80 - 200" fails range validation, abandoning the line misses a valid client field later on the same line.
  • Using \d instead of [0-9] in Python. Python's \d matches Unicode digits like "٣" and int("٣") returns 3, silently accepting non-ASCII log text.
  • Merging per-file top-5 lists instead of full count maps. An IP ranked 6th in every individual file can easily be #1 in total volume across all files.

Alternative approaches

  • Bounded min-heap (heapq.nsmallest(5, ranked)): Keeps only the 5 best tuples in a min-heap (a binary tree that maintains the smallest item at the root in logarithmic time), reducing the ranking phase from O(D log D) to O(D log 5) = O(D). With D <= 200,000, Python's C-level list.sort() is already under a tenth of a second, though the heap shines when D reaches tens of millions.
  • Space-delimited token scanner: Splitting each line on " " and scanning tokens left-to-right avoids regexes completely, at the cost of ~40 lines of manual prefix/suffix boundary checks (used in tests.py as an independent reference oracle).

Follow-up questions

  • How would you process multi-gigabyte compressed log archives on disk without loading all log lines into memory? Stream .tar.gz or .gz files sequentially line by line—for instance with tarfile.open(path, mode="r|gz") (using | so Python decompresses a forward-only byte stream without seeking or buffering entire members) and raw_line.decode("utf-8", errors="replace") so a stray non-UTF-8 byte never aborts the job. Each line is parsed by client_ip(line) and immediately garbage-collected, keeping peak memory proportional only to O(D) distinct IPv4 keys rather than the multi-gigabyte uncompressed archive size.
  • How would you compute the top five client IPs across hundreds of gigabytes of logs spread across many machines or under tight RAM limits? Across a cluster, run a two-stage MapReduce aggregation: each mapper streams its log shards into a local ip -> count hash map and partitions (ip, partial_count) pairs to reducer hash(ip) % R (never truncate to top-5 per shard, since a 6th-place IP in every shard can win globally), after which each reducer emits its exact top 5 to a single coordinator. On a single RAM-constrained host where even O(D) counters exceed memory, run a bounded Misra-Gries heavy-hitters sketch of k counters in pass 1 to isolate heavy candidates within error N / (k + 1), followed by a second streaming pass counting exact totals for those candidate IPs.
  • Why does appearing in the top five request counts not prove that an IPv4 address is malicious, and what additional signals would you check before blocking it? High request count measures socket concentration, not intent: corporate/university NAT gateways, mobile Carrier-Grade NAT, reverse proxies or CDN edges (if peer IPs were logged instead of trusted X-Forwarded-For client headers), and legitimate partner webhooks or uptime monitors routinely top traffic tables. Before blocking, check whether the IP's per-minute rate spiked abruptly relative to its 24-hour baseline, inspect status distributions (401/403 bursts on auth endpoints or 404 enumeration), verify ASN/reverse-DNS ownership, and favor scoped rate limiting over a blanket firewall drop that could blackhole thousands of legitimate users behind shared NAT.

Follow-up questions

Similar questions

More Render interview questions

All 3 Render questions →