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:
- Order results by numeric request count descending (
"12"comes before"9"). - 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"). - 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):METHODbegins at a word boundary (not attached to preceding word characters, so"FORGET"does not match"GET") and is one ofGET,POST,PUT,PATCH,DELETE,HEAD, orOPTIONS.URLis a non-empty token containing no whitespace characters, separated fromMETHODandHTTP/versionby single spaces.versionis1.0,1.1, or2.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.Dconsists of four ASCII decimal octets, each in0..255, with no leading zeros on multi-digit octets (0is valid;01is invalid).portis an ASCII decimal integer in1..65535.statusis 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 most20,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-9are valid in IPv4 octets, port numbers, HTTP versions, and status codes.
Step-by-step walkthrough
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 (withcountformatted as a base-10 string), sorted by:- Request count descending as integers (
12comes before9). - Numeric IPv4 address ascending on ties (
198.51.100.7comes before198.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(METHODinGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS;versionin1.0, 1.1, 2.0). - Client portion later on the same line:
from A.B.C.D:port - status(A..Din0..255with no leading zeros on multi-digit octets,portin1..65535,statusof 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.- Request count descending as integers (
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\dbecause Python's\dalso matches Unicode digits from non-ASCII scripts (such as Arabic-Indic"٣"), whichint()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])" )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 in0..255. BecauseCLIENT_REonly 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 like0or65536.We write a helper
ipv4_octets(ip)that validates each octet (0..255, no leading zero whenlen(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 forCLIENT_REstarting atrequest.end()(right after the earliest valid request match, preserving the widest suffix of the line). And we iterate withfinditerrather than stopping at the first.search()hit: if a line has an invalid decoy likefrom 256.1.1.1:80 - 200ahead of a realfrom 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 NoneAggregate 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, makingipan 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
countplaces 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- Negating
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.99never enterscounts(it only appeared in a TLS retry diagnostic),198.51.100.14merges ports52310and52311including a503response into"2", and numeric octet tie-breaking orders.7ahead of.102.Stream compressed archives and interpret traffic volume safely
When inspecting multi-gigabyte
.tar.gzlog 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 onlycountsso memory staysO(D)forDdistinct 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 countsEqually 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/404bursts), endpoint targeting, and ASN ownership before applying rate limits or blocks.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
Lis the total number of characters across all log lines andDis the number of distinct valid client IPv4 addresses (Dis at most the number of lines, up to200,000). We scan each line left-to-right with two non-backtracking patterns (\S+stops at the next space) and do anO(1)dictionary update per valid line, costingO(L)total; then we sortDfixed-size 4-octet tuples inO(D log D)time. - Space: O(D) auxiliary memory beyond the input
fileslist, becausecountsandrankedstore at most one entry per distinct client IPv4 address. When streaming a compressed archive line by line from disk, total RAM staysO(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.255comes before10.0.0.0and198.51.100.7comes before198.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:
404and503responses, private ranges (10.x.x.x,192.168.x.x),0.0.0.0,255.255.255.255, port1, and port65535all count. - Wrong field order on a line:
upstream from 198.51.100.99:44100 - 200 before GET /x HTTP/1.1hasfrombefore the HTTP request, so searching afterrequest.end()properly ignores it. - Invalid decoy
frombefore a validfrom: OnGET /a HTTP/1.1 from 256.1.1.1:80 - 200 from 1.2.3.4:80 - 200,256.1.1.1fails octet validation (256 > 255), andfinditercontinues to find and count1.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
\band(?![0-9]),"FORGET"matches"GET","HTTP/1.10"matches"HTTP/1.1", and"- 2000"matches"- 200". - Stopping after the first regex hit of
CLIENT_REwith.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
\dinstead of[0-9]in Python. Python's\dmatches Unicode digits like"٣"andint("٣")returns3, 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 fromO(D log D)toO(D log 5) = O(D). WithD <= 200,000, Python's C-levellist.sort()is already under a tenth of a second, though the heap shines whenDreaches 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 intests.pyas 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.gzor.gzfiles sequentially line by line—for instance withtarfile.open(path, mode="r|gz")(using|so Python decompresses a forward-only byte stream without seeking or buffering entire members) andraw_line.decode("utf-8", errors="replace")so a stray non-UTF-8 byte never aborts the job. Each line is parsed byclient_ip(line)and immediately garbage-collected, keeping peak memory proportional only toO(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 -> counthash map and partitions(ip, partial_count)pairs to reducerhash(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 evenO(D)counters exceed memory, run a bounded Misra-Gries heavy-hitters sketch ofkcounters in pass 1 to isolate heavy candidates within errorN / (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-Forclient 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/403bursts on auth endpoints or404enumeration), 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
- How would you process multi-gigabyte compressed log archives on disk without loading all log lines into memory?
- How would you compute the top five client IPs across hundreds of gigabytes of logs spread across many machines or under tight RAM limits?
- 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?
Similar questions
- Counting Throttled Requests in Sliding Windows
- Defending an API with Layered Rate Limiting
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance