Aggregate HTTP Logs to Identify Top Client Addresses
StringsModel answerLast updated
Parse multi-file request logs to extract and rank the five IPv4 addresses that generated the most completed HTTP requests.
You're investigating an API traffic spike and need to identify which client addresses generated the most load. You have access to log data split across multiple files, each containing a mix of HTTP request records and operational messages.
Write a function top_request_ips(files: string[][]) -> string[][] that processes these logs and returns the top five client IPv4 addresses by request volume.
Input Format
filesis an array of file contents; each file is represented as an array of log lines (strings)- Maximum 20 files, 200,000 total lines, 20,000,000 total characters
What Counts as a Request
A line represents a completed HTTP request if it contains all of these elements in order:
- An HTTP method:
GET,POST,PUT,PATCH,DELETE,HEAD, orOPTIONS(as a complete word) - A URL (non-whitespace characters)
- An HTTP version:
HTTP/1.0,HTTP/1.1, orHTTP/2.0 - The literal text
from - An IPv4 address in dotted-decimal notation (0-255 per octet, no leading zeros except
0itself) - A colon and port number (1-65535)
- A space, hyphen, space, then exactly three digits (the HTTP status code)
Example valid request line:
time="t" msg="GET https://api.example/users HTTP/1.1 from 192.168.1.5:443 - 200 1.2KB"
Lines that mention an IP address but lack the full request structure should be ignored. For instance, Client IP="10.0.0.5:80" redirect diagnostics or background messages like "scheduler from 10.0.0.1" do not count.
Counting Rules
- Count each matching line exactly once
- Group by IP address only; ignore the port number
- Count all status codes (2xx, 4xx, 5xx, etc.)
- The same IP appearing in different files or with different ports contributes to a single total
Output Format
Return an array of [ip, count] pairs, where:
countis a decimal string- Results are ordered by count (descending), then by numeric IPv4 value (ascending) for ties
- Numeric IPv4 comparison treats each octet as an integer:
10.0.0.9comes before10.0.0.10 - Return fewer than five rows if fewer than five distinct IPs are found
Example
files = [[
'time="t" msg="GET https://api.example/a HTTP/2.0 from 10.0.0.2:12 - 200 4B"',
'time="t" msg="redirecting" Client IP="10.0.0.9:15"',
'time="t" msg="POST https://api.example/b HTTP/1.1 from 10.0.0.2:13 - 500 0B"'
], [
'time="t" msg="GET https://api.example/c HTTP/1.1 from 10.0.0.10:14 - 200 4B"',
'time="t" msg="no pending executions"'
]]
// Result: 10.0.0.2 appears twice (200 and 500), 10.0.0.10 once
// The "Client IP=" line is ignored
result = [["10.0.0.2","2"], ["10.0.0.10","1"]]
Discussion Questions
- How would you process logs stored as compressed archive files without loading everything into memory?
- What additional signals would you examine before concluding that a high-volume IP address is malicious?
Hints
Hint 1
Use regex to match the full request pattern, not just the presence of an IP address
Hint 2
A cheap substring precheck like `' from ' in line` can skip most non-request lines before running the full regex
Hint 3
For numeric IPv4 ordering, split each address into four integers and compare those tuples
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is distinguishing actual request records from operational log messages that happen to mention IP addresses. A line counts only when it contains the complete signature of an HTTP request event.
Pattern Matching Strategy
Build a regular expression that captures the required structure:
- Method token – use a word boundary or negative lookbehind to avoid matching
FORGETasGET - URL – match non-whitespace
- HTTP version – match
1.0,1.1, or2.0with a negative lookahead to reject1.10 - Flexible gap – use
.*?to accommodate varying quote escaping and intermediate text - Client marker – literal
from - IPv4 address – each octet matches
0through255without leading zeros - Port – one to five digits starting with
1-9, validated separately to ensure ≤ 65535 - Status – exactly three digits with negative lookahead to prevent matching longer numbers
The pattern for a single octet:
25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d
This accepts 0, 9, 42, 199, 255 but rejects 01, 256, 300.
Algorithm
- Initialize a counter (hash map) for IP addresses
- For each line in each file:
- Quick check: if
" from "is not in the line, skip it - Apply the regex; if no match, skip
- Validate the port is ≤ 65535
- Extract the IP (without port) and increment its count
- Quick check: if
- Select the top five:
- Use a min-heap or sort by
(-count, numeric_ip_tuple) - The numeric IP tuple is
(octet1, octet2, octet3, octet4)as integers
- Use a min-heap or sort by
- Format output as
[ip_string, count_string]pairs
Complexity
- Time: O(C + U log 5), where C is total characters and U is distinct IPs
- Regex scanning is linear in practice; the precheck skips most lines
- Extracting the top five from U entries with a heap is O(U log 5)
- Space: O(U) for the counter dictionary
Edge Cases
- Empty input or no matching lines → return
[] - Fewer than five distinct IPs → return all
- Ties in count → break by numeric IP order (e.g.,
2.0.0.0before10.0.0.0) - Same IP with different ports or across files → aggregate into one count
- Non-2xx statuses → still count
Client IP=diagnostic lines → ignored because they lack the full request structure- Out-of-spec input (IPv6, port 0, leading zeros) → won't match the pattern
Python Implementation
import re
import heapq
from collections import Counter
from typing import List
# Octet pattern: 0-255 with no leading zeros except "0"
_OCTET = r"(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)"
# Full request pattern
_REQUEST_PATTERN = re.compile(
r"(?<![A-Za-z])(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) "
r"\S+ HTTP/(?:1\.0|1\.1|2\.0)(?!\d)"
r".*? from "
r"(" + _OCTET + r"(?:\." + _OCTET + r"){3})"
r":([1-9]\d{0,4}) - \d{3}(?!\d)"
)
def ip_to_tuple(ip: str) -> tuple:
"""Convert IP string to tuple of integers for numeric comparison."""
return tuple(int(octet) for octet in ip.split("."))
def top_request_ips(files: List[List[str]]) -> List[List[str]]:
ip_counts = Counter()
for file_lines in files:
for line in file_lines:
# Fast precheck to skip most non-request lines
if " from " not in line:
continue
match = _REQUEST_PATTERN.search(line)
if not match:
continue
# Validate port range (regex allows 1-99999, we need 1-65535)
port = int(match.group(2))
if port > 65535:
continue
# Extract IP and count it
ip = match.group(1)
ip_counts[ip] += 1
# Select top 5 by (-count, numeric IP tuple)
top_five = heapq.nsmallest(
5,
ip_counts.items(),
key=lambda item: (-item[1], ip_to_tuple(item[0]))
)
return [[ip, str(count)] for ip, count in top_five]
Processing Real Archives Incrementally
In production, logs typically come as compressed files (.gz, .tar.gz) or rotated log archives. To handle these without memory overflow:
Stream files one at a time:
import gzip
import tarfile
def process_archive(archive_path: str):
ip_counts = Counter()
with tarfile.open(archive_path, "r|gz") as tar:
for member in tar:
if not member.isfile():
continue
f = tar.extractfile(member)
for line in f:
# Process line (decode bytes, apply regex, count)
pass
return ip_counts
Key techniques:
- Use streaming tarfile mode
"r|gz"to avoid loading the entire archive - Process one line at a time with
for line in file - Memory usage becomes O(U + longest_line), independent of archive size
- For very large U (millions of IPs), use hash-partitioning or streaming sketches like Count-Min + heap
Parallelism:
- Count each file in a separate worker process
- Merge the resulting Counters (counting is associative)
- Extract top-5 from the merged counts
High Volume ≠ Malicious
The output shows request volume, not intent. Before taking action against a high-volume IP:
Consider legitimate explanations:
- NAT and proxies – corporate networks, carrier-grade NAT, VPNs, and CDNs can aggregate thousands of users behind one IP
- Infrastructure – load balancers, reverse proxies, health checks, and internal service-to-service calls
- Retry storms – a client retrying after server errors (your 500s) or network issues
- Batch jobs – scheduled integrations, ETL processes, monitoring systems
Corroborating signals for malicious activity:
- High error rates (401, 403, 404 patterns suggesting scanning)
- Unusual endpoint diversity or sequential parameter probing
- Timing regularity characteristic of automated tools
- Mismatch with user-agent or authorization identity
- Deviation from that IP's historical baseline
- Threat intelligence or ASN reputation data
Treat this analysis as a starting point for investigation, not a conclusion. Combine it with rate patterns, authentication context, and behavioral baselines before implementing blocks or rate limits.