TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Mini Project: A One-Pass Log Analyser

Mini Project: A One-Pass Log Analyser

A web server writes one line per request. Questions about the log arrive constantly: how many different users came today, which pages are the most popular, what share of the traffic is API calls or comes from one crawler? Keeping the whole log, or an exact table per question, grows without bound. In this project you build a one-pass log analyser whose memory is fixed in advance, from the sketches of the course:

Every answer is compared with the exact one. The last step puts the three summaries into one class and merges the summaries of two servers, as a distributed system would (Mergeable Summaries).

Each step is a complete program. All of them start with the same log generator, so you can run any step on its own; every random choice comes from a seeded generator, so the numbers below are exactly what you will see.

Step 1: The log and the exact answers

The generator writes 60 000 lines of the form second user page. Pages follow a Zipf-like law (a few very popular pages, a long tail), users a flatter one, and a crawler, crawler-7, sends about 3% of the requests. A quarter of the pages are API endpoints. The exact baseline keeps a set of users and a counter per page.

python · try it yourself
import random
from collections import Counter

def make_log(lines=60000, seed=2026):
    """A synthetic web log: 'second user page' per line, Zipf-like pages and users, plus a busy crawler."""
    rng = random.Random(seed)
    def zipf_cum(n, s):
        cum, t = [], 0.0
        for i in range(n):
            t += 1 / (i + 1) ** s
            cum.append(t)
        return cum
    page_cum, user_cum = zipf_cum(3000, 1.1), zipf_cum(40000, 0.7)
    pages = rng.choices(range(3000), cum_weights=page_cum, k=lines)
    users = rng.choices(range(40000), cum_weights=user_cum, k=lines)
    log = []
    for t in range(lines):
        user = "crawler-7" if rng.random() < 0.03 else f"u{users[t]}"
        page = f"/api/v1/item/{pages[t]}" if pages[t] % 4 == 0 else f"/docs/{pages[t]}"
        log.append(f"{t // 20} {user} {page}")
    return log

log = make_log()
print(len(log), "lines; the first three:")
for line in log[:3]:
    print("  ", line)
users, pages = set(), Counter()
api = 0
for line in log:
    _, user, page = line.split()
    users.add(user)
    pages[page] += 1
    api += page.startswith("/api/")
print(f"exact: {len(users)} distinct users, {len(pages)} distinct pages, API share {api / len(log):.4f}")
print("top 5 pages:", pages.most_common(5))
print(f"memory of the exact answers: {len(users) + len(pages)} table entries")
60000 lines; the first three:
   0 u3231 /api/v1/item/0
   0 u5137 /api/v1/item/16
   0 u138 /docs/18
exact: 23044 distinct users, 2770 distinct pages, API share 0.3495
top 5 pages: [('/api/v1/item/0', 9880), ('/docs/1', 4599), ('/docs/2', 3013), ('/docs/3', 2102), ('/api/v1/item/4', 1740)]
memory of the exact answers: 25814 table entries

The exact answers need a table entry for every user and every page, about 26 000 entries here, and the tables grow with the log. Worse, a new question (what share of requests came in the last ten minutes?) needs the full log.

Step 2: Distinct users with HyperLogLog

Python's built-in hash() of a string is randomized per process, so the analyser hashes user names itself: 8 bytes at a time through the splitmix64 mixer. Then HyperLogLog runs with three register counts.

python · try it yourself
import math, random

def make_log(lines=60000, seed=2026):
    """A synthetic web log: 'second user page' per line, Zipf-like pages and users, plus a busy crawler."""
    rng = random.Random(seed)
    def zipf_cum(n, s):
        cum, t = [], 0.0
        for i in range(n):
            t += 1 / (i + 1) ** s
            cum.append(t)
        return cum
    page_cum, user_cum = zipf_cum(3000, 1.1), zipf_cum(40000, 0.7)
    pages = rng.choices(range(3000), cum_weights=page_cum, k=lines)
    users = rng.choices(range(40000), cum_weights=user_cum, k=lines)
    log = []
    for t in range(lines):
        user = "crawler-7" if rng.random() < 0.03 else f"u{users[t]}"
        page = f"/api/v1/item/{pages[t]}" if pages[t] % 4 == 0 else f"/docs/{pages[t]}"
        log.append(f"{t // 20} {user} {page}")
    return log

MASK = (1 << 64) - 1
def mix64(x):
    x = (x + 0x9E3779B97F4A7C15) & MASK
    x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
    return x ^ (x >> 31)

def str_hash(s, salt=0):
    """A deterministic 64-bit hash of a string (Python's built-in hash() is salted per run)."""
    data, h = s.encode(), salt
    for i in range(0, len(data), 8):                 # 8 bytes at a time
        h = mix64(h ^ int.from_bytes(data[i:i + 8], "little"))
    return mix64(h ^ len(data))

class HyperLogLog:
    def __init__(self, p=10, salt=0):
        self.p, self.m, self.salt = p, 1 << p, salt
        self.M = [0] * self.m
    def add(self, item):
        h = str_hash(item, self.salt)
        j, rest = h >> (64 - self.p), h & ((1 << (64 - self.p)) - 1)
        self.M[j] = max(self.M[j], 64 - self.p - rest.bit_length() + 1)
    def estimate(self):
        m = self.m
        E = 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in self.M)
        zeros = self.M.count(0)
        return m * math.log(m / zeros) if E <= 2.5 * m and zeros else E

log = make_log()
exact = len({line.split()[1] for line in log})
print(f"exact distinct users: {exact}")
for p in [6, 10, 12]:
    h = HyperLogLog(p)
    for line in log:
        h.add(line.split()[1])
    est = h.estimate()
    print(f"HyperLogLog, {h.m:4} registers ({h.m * 6 // 8:4} bytes): {est:8.0f}  "
          f"error {est / exact - 1:+.1%}  (typical {1.04 / math.sqrt(h.m):.1%})")
exact distinct users: 23044
HyperLogLog,   64 registers (  48 bytes):    27944  error +21.3%  (typical 13.0%)
HyperLogLog, 1024 registers ( 768 bytes):    22841  error -0.9%  (typical 3.2%)
HyperLogLog, 4096 registers (3072 bytes):    23497  error +2.0%  (typical 1.6%)

The errors are consistent with 1.04/m1.04/\sqrt{m}: a single run can be off by one or two standard errors (the 64-register sketch here by about 1.6). With 4096 registers, 3 KB of memory, the estimate is within 2% and would stay at that accuracy for a log of billions of lines.

Step 3: Top pages with Misra-Gries and Space-Saving

Both summaries use k=50k = 50 (k−1=49k - 1 = 49 counters for Misra-Gries, 50 for Space-Saving). Every page with more than m/k=1200m/k = 1200 views is guaranteed to be kept by both.

python · try it yourself
import random
from collections import Counter

def make_log(lines=60000, seed=2026):
    """A synthetic web log: 'second user page' per line, Zipf-like pages and users, plus a busy crawler."""
    rng = random.Random(seed)
    def zipf_cum(n, s):
        cum, t = [], 0.0
        for i in range(n):
            t += 1 / (i + 1) ** s
            cum.append(t)
        return cum
    page_cum, user_cum = zipf_cum(3000, 1.1), zipf_cum(40000, 0.7)
    pages = rng.choices(range(3000), cum_weights=page_cum, k=lines)
    users = rng.choices(range(40000), cum_weights=user_cum, k=lines)
    log = []
    for t in range(lines):
        user = "crawler-7" if rng.random() < 0.03 else f"u{users[t]}"
        page = f"/api/v1/item/{pages[t]}" if pages[t] % 4 == 0 else f"/docs/{pages[t]}"
        log.append(f"{t // 20} {user} {page}")
    return log

class MisraGries:
    def __init__(self, k):
        self.k, self.C = k, {}
    def add(self, x):
        C = self.C
        if x in C:
            C[x] += 1
        elif len(C) < self.k - 1:
            C[x] = 1
        else:
            for y in list(C):
                C[y] -= 1
                if C[y] == 0:
                    del C[y]

class SpaceSaving:
    def __init__(self, k):
        self.k, self.C, self.err = k, {}, {}
    def add(self, x):
        C = self.C
        if x in C:
            C[x] += 1
        elif len(C) < self.k:
            C[x], self.err[x] = 1, 0
        else:
            y = min(C, key=lambda z: (C[z], z))
            c = C.pop(y)
            self.err.pop(y)
            C[x], self.err[x] = c + 1, c

log = make_log()
k = 50
mg, ss, exact = MisraGries(k), SpaceSaving(k), Counter()
for line in log:
    page = line.split()[2]
    mg.add(page); ss.add(page); exact[page] += 1
m = len(log)
print(f"m = {m}, k = {k}: pages above m/k = {m // k} views: {sum(c > m / k for c in exact.values())}")
print("rank  page                 exact   Misra-Gries   Space-Saving (error bound)")
for r, (page, c) in enumerate(exact.most_common(8), 1):
    print(f"{r:4}  {page:18} {c:7}   {mg.C.get(page, 0):11}   {ss.C.get(page, 0):12} ({ss.err.get(page, 0)})")
top_ss = sorted(ss.C, key=lambda p: -ss.C[p])[:8]
print("Space-Saving's top 8 == exact top 8:", top_ss == [p for p, _ in exact.most_common(8)])
m = 60000, k = 50: pages above m/k = 1200 views: 6
rank  page                 exact   Misra-Gries   Space-Saving (error bound)
   1  /api/v1/item/0        9880          9047           9880 (0)
   2  /docs/1               4599          3766           4599 (0)
   3  /docs/2               3013          2180           3013 (0)
   4  /docs/3               2102          1269           2102 (0)
   5  /api/v1/item/4        1740           908           1741 (2)
   6  /docs/5               1385           554           1387 (4)
   7  /docs/6               1155           324           1157 (3)
   8  /docs/7               1002           169           1002 (0)
Space-Saving's top 8 == exact top 8: True

Misra-Gries undercounts every page by the same amount here (about 830, its number of decrement steps), so its ranking is right but its counts are low; its guarantee is an undercount of at most m/k=1200m/k = 1200. Space-Saving overcounts by at most its stored error bound, which is 0 to 4 for these pages because they entered early and were never evicted: its counts are exact or certified within a few views, and its top 8 matches the exact top 8. This is the usual experience in practice, and it is why top-kk dashboards favour Space-Saving.

Step 4: A reservoir for unplanned questions

A reservoir of 500 lines answers questions that were not known when the log was written. Each share is estimated by its frequency in the sample, with a standard error of p(1−p)/500\sqrt{p(1-p)/500}.

python · try it yourself
import math, random

def make_log(lines=60000, seed=2026):
    """A synthetic web log: 'second user page' per line, Zipf-like pages and users, plus a busy crawler."""
    rng = random.Random(seed)
    def zipf_cum(n, s):
        cum, t = [], 0.0
        for i in range(n):
            t += 1 / (i + 1) ** s
            cum.append(t)
        return cum
    page_cum, user_cum = zipf_cum(3000, 1.1), zipf_cum(40000, 0.7)
    pages = rng.choices(range(3000), cum_weights=page_cum, k=lines)
    users = rng.choices(range(40000), cum_weights=user_cum, k=lines)
    log = []
    for t in range(lines):
        user = "crawler-7" if rng.random() < 0.03 else f"u{users[t]}"
        page = f"/api/v1/item/{pages[t]}" if pages[t] % 4 == 0 else f"/docs/{pages[t]}"
        log.append(f"{t // 20} {user} {page}")
    return log

class Reservoir:
    def __init__(self, k, seed):
        self.k, self.seen, self.R, self.rng = k, 0, [], random.Random(seed)
    def add(self, x):
        self.seen += 1
        if len(self.R) < self.k:
            self.R.append(x)
        else:
            j = self.rng.randrange(self.seen)
            if j < self.k:
                self.R[j] = x

log = make_log()
res = Reservoir(500, seed=1)
for line in log:
    res.add(line)
questions = {
    "share of API requests": lambda line: line.split()[2].startswith("/api/"),
    "share of crawler traffic": lambda line: line.split()[1] == "crawler-7",
    "share of requests in the last 10 minutes": lambda line: int(line.split()[0]) >= 2400,
}
print(f"reservoir of {res.k} lines out of {res.seen}; a few of them:")
for line in sorted(res.R, key=lambda l: int(l.split()[0]))[:3]:
    print("  ", line)
print("question                                   exact    sample   +- 2 std. errors")
for q, pred in questions.items():
    exact = sum(map(pred, log)) / len(log)
    p = sum(map(pred, res.R)) / res.k
    print(f"{q:40} {exact:7.4f}   {p:7.4f}   {2 * math.sqrt(p * (1 - p) / res.k):.4f}")
reservoir of 500 lines out of 60000; a few of them:
   10 u11976 /docs/322
   14 u14 /api/v1/item/4
   19 u376 /api/v1/item/0
question                                   exact    sample   +- 2 std. errors
share of API requests                     0.3495    0.3640   0.0430
share of crawler traffic                  0.0301    0.0220   0.0131
share of requests in the last 10 minutes  0.2000    0.2340   0.0379

All three estimates are within two standard errors of the truth. A sample is weak for rare events (the crawler's 3% is estimated from 11 sampled lines) and useless for the long tail of pages, which is exactly where HyperLogLog and the heavy-hitter summaries take over: each tool answers the questions it is built for.

Step 5: One analyser, two servers, one merge

The final analyser combines HyperLogLog (4096 registers), Misra-Gries (k=50k = 50) and a reservoir of 500 lines. The reservoir is the keyed version: each line gets a random key and the sample keeps the 500 smallest keys, which makes it mergeable. Two servers each analyse half of the traffic (even and odd seconds); their summaries are merged with the register-wise maximum, the Misra-Gries merge (add, then subtract the kk-th largest count) and "keep the 500 smallest keys of both".

python · try it yourself
import heapq, math, random
from collections import Counter

def make_log(lines=60000, seed=2026):
    """A synthetic web log: 'second user page' per line, Zipf-like pages and users, plus a busy crawler."""
    rng = random.Random(seed)
    def zipf_cum(n, s):
        cum, t = [], 0.0
        for i in range(n):
            t += 1 / (i + 1) ** s
            cum.append(t)
        return cum
    page_cum, user_cum = zipf_cum(3000, 1.1), zipf_cum(40000, 0.7)
    pages = rng.choices(range(3000), cum_weights=page_cum, k=lines)
    users = rng.choices(range(40000), cum_weights=user_cum, k=lines)
    log = []
    for t in range(lines):
        user = "crawler-7" if rng.random() < 0.03 else f"u{users[t]}"
        page = f"/api/v1/item/{pages[t]}" if pages[t] % 4 == 0 else f"/docs/{pages[t]}"
        log.append(f"{t // 20} {user} {page}")
    return log

MASK = (1 << 64) - 1
def mix64(x):
    x = (x + 0x9E3779B97F4A7C15) & MASK
    x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
    return x ^ (x >> 31)

def str_hash(s):
    data, h = s.encode(), 0
    for i in range(0, len(data), 8):
        h = mix64(h ^ int.from_bytes(data[i:i + 8], "little"))
    return mix64(h ^ len(data))

class LogAnalyser:
    """One pass, fixed memory: HyperLogLog (users), Misra-Gries (pages), keyed reservoir (lines)."""
    def __init__(self, p=12, k=50, sample=500, seed=0):
        self.p, self.k, self.sample = p, k, sample
        self.M = [0] * (1 << p)
        self.C = {}
        self.res = []                                  # max-heap by key (negated): the smallest keys
        self.rng = random.Random(seed)
        self.lines = 0
    def add(self, line):
        self.lines += 1
        _, user, page = line.split()
        h = str_hash(user)                             # HyperLogLog
        j, rest = h >> (64 - self.p), h & ((1 << (64 - self.p)) - 1)
        self.M[j] = max(self.M[j], 64 - self.p - rest.bit_length() + 1)
        C = self.C                                     # Misra-Gries
        if page in C:
            C[page] += 1
        elif len(C) < self.k - 1:
            C[page] = 1
        else:
            for y in list(C):
                C[y] -= 1
                if C[y] == 0:
                    del C[y]
        key = self.rng.random()                        # reservoir: keep the smallest random keys
        if len(self.res) < self.sample:
            heapq.heappush(self.res, (-key, line))
        elif key < -self.res[0][0]:
            heapq.heapreplace(self.res, (-key, line))
    def merge(self, other):
        self.lines += other.lines
        self.M = [max(a, b) for a, b in zip(self.M, other.M)]
        S = Counter(self.C)
        S.update(other.C)
        if len(S) >= self.k:
            ck = sorted(S.values(), reverse=True)[self.k - 1]
            S = Counter({x: c - ck for x, c in S.items() if c > ck})
        self.C = dict(S)
        self.res = heapq.nlargest(self.sample, self.res + other.res)   # largest -key = smallest key
        heapq.heapify(self.res)
    def report(self):
        m = len(self.M)
        E = 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in self.M)
        zeros = self.M.count(0)
        users = m * math.log(m / zeros) if E <= 2.5 * m and zeros else E
        top = sorted(self.C.items(), key=lambda kv: -kv[1])[:5]
        api = sum(l.split()[2].startswith("/api/") for _, l in self.res) / len(self.res)
        return users, top, api

log = make_log()
a, b = LogAnalyser(seed=1), LogAnalyser(seed=2)
for line in log:                                       # two servers: even and odd seconds
    (a if int(line.split()[0]) % 2 == 0 else b).add(line)
a.merge(b)
users, top, api = a.report()
exact_users = len({l.split()[1] for l in log})
exact_pages = Counter(l.split()[2] for l in log)
exact_api = sum(l.split()[2].startswith("/api/") for l in log) / len(log)
print(f"lines: {a.lines}")
print(f"distinct users: estimate {users:.0f}, exact {exact_users} ({users / exact_users - 1:+.1%})")
print("top pages (Misra-Gries lower bound / exact):")
for page, c in top:
    print(f"   {page:18} >= {c:5}   exact {exact_pages[page]}")
print(f"API share from the merged sample: {api:.3f}, exact {exact_api:.3f}")
mem = len(a.M) + 2 * len(a.C) + len(a.res)
print(f"summary size: {len(a.M)} registers + {len(a.C)} counters + {len(a.res)} sampled lines; "
      f"exact answers need {exact_users + len(exact_pages)} table entries and the full log for new questions")
lines: 60000
distinct users: estimate 23497, exact 23044 (+2.0%)
top pages (Misra-Gries lower bound / exact):
   /api/v1/item/0     >=  9047   exact 9880
   /docs/1            >=  3766   exact 4599
   /docs/2            >=  2180   exact 3013
   /docs/3            >=  1269   exact 2102
   /api/v1/item/4     >=   908   exact 1740
API share from the merged sample: 0.338, exact 0.349
summary size: 4096 registers + 21 counters + 500 sampled lines; exact answers need 25814 table entries and the full log for new questions

The merged summary answers all three questions as well as one server seeing everything would: the HyperLogLog registers are identical to the single-pass ones (the same estimate as in Step 2), the Misra-Gries lower bounds here even coincide with the single-pass values of Step 3, and the merged sample is a uniform sample of all 60 000 lines. Its size is fixed, about 4100 small numbers and 500 lines, whatever the length of the log.

Ideas for extensions

  • Time windows. Keep one analyser per hour and merge the last 24 for a daily view; the merge guarantees make the daily answers as accurate as the hourly ones.
  • Distinct users per page for the top pages: a small HyperLogLog per Misra-Gries candidate.
  • Deletions (requests later marked as fraudulent and removed): replace Misra-Gries by count-min with a dyadic hierarchy, which is linear.
  • Quantiles of response times: the dyadic count-min of Heavy Hitters in Turnstile Streams answers them with additive rank error.

Test yourself

Why does the analyser hash user names with its own function instead of Python's built-in hash()?

  1. The built-in is slower
  2. The built-in hash of a string is randomized per process, so two runs or two servers would produce incompatible sketches that cannot be merged or reproduced
  3. The built-in returns negative numbers
  4. HyperLogLog needs 32-bit hashes

In Step 3, why are Space-Saving's counts for the top pages exact or nearly exact while Misra-Gries's are all about 830 too low?

  1. Space-Saving uses more memory
  2. Misra-Gries subtracts one from every counter in each decrement step, while the early heavy pages in Space-Saving were never evicted and so carry error bounds near 0
  3. Misra-Gries is randomized
  4. The pages are sorted

What makes the reservoir in Step 5 mergeable?

  1. It stores every line
  2. Each line has a random key and the sample is the set of smallest keys, so the sample of a union is the smallest keys of the two samples together
  3. It uses Algorithm L
  4. It is sorted by time