The 2 GB Log File at 11 PM
CI checks the runnable examples on this page every night, and they currently run on Zig 0.18.0-dev.1272+2ff397f75. Nothing checks the plain code blocks, and they may not compile now.
10:52 PM
Shivam’s phone buzzed on the kitchen table. The alert was the one that nobody wants: Checkout error rate above 5%.
Shivam was on call this week. When production breaks at night, the person on call repairs the problem. This week, that person was Shivam.
Shivam opened the laptop. A message from Urvashi in support was already there.
Customers say payment hangs and then fails. Started maybe 20 minutes ago?
“Maybe” was not sufficient. Shivam had to know which part of the site was slow, and when the problem started.
10:58 PM
Shivam logged in to the web server, web-03, and examined the access log.
$ ls -lh /var/log/shop/access.log
-rw-r----- 1 shop shop 2.0G Oct 3 22:58 /var/log/shop/access.log
The log was two gigabytes: fifty million lines, with one line for each request. Each line had this shape:
2026-10-03T22:41:07Z POST /api/checkout 504 5000
The fields are the time, the method, the path, the status code, and the duration of the request in milliseconds.
Shivam knew what the report had to show:
- The number of requests for each status code.
- The endpoint that was slow.
- The time of the first
504. A504means that the request timed out.
The server had awk. The server did not have Python. And this week, the rules let nobody install software on production servers.
Shivam could write the report in awk. But an average for each endpoint, a maximum and “the first 504” make a long awk line.
Shivam wanted a program to test on the laptop first. Then Shivam could trust the program on the server. Thus Shivam opened a new file: logscan.zig.
11:04 PM: one line at a time
Shivam wrote the smallest part first: a function that splits one line of text into fields.
/// Returns null for a line that the program cannot use. For an aborted request,
/// the log has `-` in place of the milliseconds. One bad line must not stop the scan.
fn parseLine(text: []const u8) ?Line {
var fields = std.mem.tokenizeScalar(u8, text, ' ');
const time = fields.next() orelse return null;
_ = fields.next() orelse return null; // the method: GET, POST
const path = fields.next() orelse return null;
const status = std.fmt.parseInt(u16, fields.next() orelse return null, 10) catch return null;
const ms = std.fmt.parseInt(u32, fields.next() orelse return null, 10) catch return null;
return .{ .time = time, .path = path, .status = status, .ms = ms };
}The function returns ?Line. The ? means “a Line, or null”.
Shivam knew that the log had bad lines. When a customer closes the tab in the middle of a request, the server writes - in place of the milliseconds.
parseInt fails on -. Thus parseLine returns null, and the caller counts the line as skipped. The caller adds one to skipped and continues to the next line.
11:10 PM: read 2 GB with 64 KiB
The server had less than 1 GB of free memory. Thus Shivam could not read the full file into memory first.
Shivam gave the reader a buffer of 64 KiB:
var buf: [64 * 1024]u8 = undefined;
var reader = file.reader(io, &buf);
The reader fills the buffer from the file. takeDelimiter('\n') returns the next line as a slice of that buffer. When the program uses all of the bytes in the buffer, the reader fills the buffer again.
The file can be of any size. The memory for the read operation stays at 64 KiB.
fn scan(r: *Report, in: *Io.Reader) !void {
while (true) {
const text = (in.takeDelimiter('\n') catch |err| switch (err) {
// A line that is longer than the buffer. Skip the line and continue.
error.StreamTooLong => {
r.bytes += try in.discardDelimiterInclusive('\n');
r.lines += 1;
r.skipped += 1;
continue;
},
else => |e| return e,
}) orelse break;
r.lines += 1;
r.bytes += text.len + 1;
const line = parseLine(text) orelse {
r.skipped += 1;
continue;
};
try r.add(line);
}
}The code has one more case. If a line is longer than the full buffer, the reader gives error.StreamTooLong. The loop skips that line and continues.
11:17 PM: the bug that almost happened
For each endpoint, Shivam kept a total in a hash map. The first version stored line.path as the key.
Then Shivam stopped. line.path is a slice of the reader’s buffer. When the reader fills the buffer again, the reader writes new bytes over those bytes.
If the map keeps those slices, each key in the map changes to different text. Nothing reports an error.
Thus the program copies each key when the key occurs for the first time:
fn add(r: *Report, line: Line) !void {
if (line.status < r.statuses.len) r.statuses[line.status] += 1;
if (line.status == 504 and r.first_504_len == 0) {
const n = @min(line.time.len, r.first_504.len);
@memcpy(r.first_504[0..n], line.time[0..n]);
r.first_504_len = n;
}
const slot = try r.endpoints.getOrPut(r.gpa, line.path);
if (!slot.found_existing) {
// `line.path` points into the buffer of the reader, and the next read
// writes over those bytes. The map keeps the key, thus the map needs its own copy.
slot.key_ptr.* = try r.gpa.dupe(u8, line.path);
slot.value_ptr.* = .{};
}
const e = slot.value_ptr;
e.requests += 1;
e.total_ms += line.ms;
e.max_ms = @max(e.max_ms, line.ms);
}In many languages, when you read a line, you get a new string that you own. In Zig, the line is a view into the reader’s buffer.
For this reason, a read of a line allocates no memory. For the same reason, you must copy a line that you want to keep.
11:24 PM: test it on the laptop
The real log was not on the laptop. Thus Shivam gave the program a second mode.
If you give the program no file name, the program writes a sample log of 50,000 lines. Then the program scans that log.
The sample is one hour of invented traffic. From 22:40, the checkout endpoint becomes slow, and some requests time out. The real endpoint did the same.
Press Run to see the report.
const std = @import("std");
const Io = std.Io;
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
var out_buf: [4096]u8 = undefined;
var stdout = Io.File.stdout().writerStreaming(io, &out_buf);
const out = &stdout.interface;
defer out.flush() catch {};
const dir = Io.Dir.cwd();
const args = try init.minimal.args.toSlice(init.arena.allocator());
const path = if (args.len > 1) args[1] else blk: {
try writeSampleLog(io, dir, "access.log", 50_000);
break :blk "access.log";
};
const file = try dir.openFile(io, path, .{});
defer file.close(io);
// The program reads all of the file through these 64 KiB. A 2 GB file and
// a 2 KB file use the same quantity of memory for the read.
var buf: [64 * 1024]u8 = undefined;
var reader = file.reader(io, &buf);
var report: Report = .init(gpa);
defer report.deinit();
try report.scan(&reader.interface);
try report.print(out, buf.len);
}
/// One request, as the server logs it:
/// `2026-10-03T22:41:07Z GET /api/checkout 504 5000`
const Line = struct {
time: []const u8,
path: []const u8,
status: u16,
ms: u32,
};
/// Returns null for a line that the program cannot use. For an aborted request,
/// the log has `-` in place of the milliseconds. One bad line must not stop the scan.
fn parseLine(text: []const u8) ?Line {
var fields = std.mem.tokenizeScalar(u8, text, ' ');
const time = fields.next() orelse return null;
_ = fields.next() orelse return null; // the method: GET, POST
const path = fields.next() orelse return null;
const status = std.fmt.parseInt(u16, fields.next() orelse return null, 10) catch return null;
const ms = std.fmt.parseInt(u32, fields.next() orelse return null, 10) catch return null;
return .{ .time = time, .path = path, .status = status, .ms = ms };
}
const Endpoint = struct {
requests: u64 = 0,
total_ms: u64 = 0,
max_ms: u32 = 0,
fn average(e: Endpoint) u64 {
return e.total_ms / e.requests;
}
};
const Report = struct {
gpa: std.mem.Allocator,
lines: u64 = 0,
bytes: u64 = 0,
skipped: u64 = 0,
/// One counter for each possible status code. It needs no allocation and no hashing.
statuses: [600]u64 = @splat(0),
endpoints: std.StringHashMapUnmanaged(Endpoint) = .empty,
first_504: [20]u8 = undefined,
first_504_len: usize = 0,
fn init(gpa: std.mem.Allocator) Report {
return .{ .gpa = gpa };
}
fn deinit(r: *Report) void {
var keys = r.endpoints.keyIterator();
while (keys.next()) |key| r.gpa.free(key.*);
r.endpoints.deinit(r.gpa);
}
fn scan(r: *Report, in: *Io.Reader) !void {
while (true) {
const text = (in.takeDelimiter('\n') catch |err| switch (err) {
// A line that is longer than the buffer. Skip the line and continue.
error.StreamTooLong => {
r.bytes += try in.discardDelimiterInclusive('\n');
r.lines += 1;
r.skipped += 1;
continue;
},
else => |e| return e,
}) orelse break;
r.lines += 1;
r.bytes += text.len + 1;
const line = parseLine(text) orelse {
r.skipped += 1;
continue;
};
try r.add(line);
}
}
fn add(r: *Report, line: Line) !void {
if (line.status < r.statuses.len) r.statuses[line.status] += 1;
if (line.status == 504 and r.first_504_len == 0) {
const n = @min(line.time.len, r.first_504.len);
@memcpy(r.first_504[0..n], line.time[0..n]);
r.first_504_len = n;
}
const slot = try r.endpoints.getOrPut(r.gpa, line.path);
if (!slot.found_existing) {
// `line.path` points into the buffer of the reader, and the next read
// writes over those bytes. The map keeps the key, thus the map needs its own copy.
slot.key_ptr.* = try r.gpa.dupe(u8, line.path);
slot.value_ptr.* = .{};
}
const e = slot.value_ptr;
e.requests += 1;
e.total_ms += line.ms;
e.max_ms = @max(e.max_ms, line.ms);
}
fn print(r: *Report, out: *Io.Writer, buffer_size: usize) !void {
try out.print("read {d} lines, {d} bytes, through a {d}-byte buffer\n", .{ r.lines, r.bytes, buffer_size });
try out.print("skipped {d} lines we could not parse\n\n", .{r.skipped});
try out.print("status requests\n", .{});
for (r.statuses, 0..) |count, status| {
if (count > 0) try out.print(" {d} {d:>8}\n", .{ status, count });
}
const Row = struct { path: []const u8, e: Endpoint };
var rows: std.ArrayList(Row) = .empty;
defer rows.deinit(r.gpa);
var it = r.endpoints.iterator();
while (it.next()) |kv| try rows.append(r.gpa, .{ .path = kv.key_ptr.*, .e = kv.value_ptr.* });
// Slowest first. If two averages are equal, the name decides. Thus the
// order never depends on the order of the hash map.
std.mem.sort(Row, rows.items, {}, struct {
fn lessThan(_: void, a: Row, b: Row) bool {
if (a.e.average() != b.e.average()) return a.e.average() > b.e.average();
return std.mem.order(u8, a.path, b.path) == .lt;
}
}.lessThan);
try out.print("\nendpoint requests avg ms max ms\n", .{});
for (rows.items) |row| {
try out.print(" {s:<15}{d:>8}{d:>8}{d:>8}\n", .{ row.path, row.e.requests, row.e.average(), row.e.max_ms });
}
if (r.first_504_len > 0) {
try out.print("\nfirst 504 at {s}\n", .{r.first_504[0..r.first_504_len]});
}
}
};
/// An invented hour of traffic from 22:00 to 23:00. From 22:40, the checkout
/// endpoint becomes slow and some requests time out. The report must find this
/// change. The seed is fixed, thus each run writes the same file.
fn writeSampleLog(io: Io, dir: Io.Dir, name: []const u8, count: u32) !void {
const file = try dir.createFile(io, name, .{});
defer file.close(io);
var buf: [8192]u8 = undefined;
var writer = file.writer(io, &buf);
const w = &writer.interface;
var prng: std.Random.Xoshiro256 = .init(2026);
const rand = prng.random();
const paths = [_][]const u8{ "/", "/api/cart", "/api/checkout", "/api/search", "/login" };
const base_ms = [_]u32{ 12, 40, 90, 60, 25 };
for (0..count) |i| {
const second: u32 = @intCast(i * 3600 / count);
const minute = second / 60;
// u32, not usize: usize is 64 bits here and 32 bits in wasm. The two
// widths get different numbers from the same seed.
const p = rand.uintLessThan(u32, paths.len);
var status: u16 = if (rand.uintLessThan(u32, 100) < 2) 404 else 200;
var ms = base_ms[p] + rand.uintLessThan(u32, base_ms[p]);
if (p == 2 and minute >= 40) {
ms *= 9;
if (rand.uintLessThan(u32, 100) < 15) {
status = 504;
ms = 5000;
}
}
try w.print("2026-10-03T22:{d:0>2}:{d:0>2}Z ", .{ minute, second % 60 });
try w.print("{s} {s} {d} ", .{ if (p == 2) "POST" else "GET", paths[p], status });
// About one request in a thousand is aborted and has no time.
if (rand.uintLessThan(u32, 1000) == 0) {
try w.writeAll("-\n");
} else {
try w.print("{d}\n", .{ms});
}
}
try w.flush();
}The program ran in your browser. The program wrote a 2 MB file. Then the program read the file again through the 64 KiB buffer.
Look at the checkout row. The average is 699 ms. The number is bad, but not very bad, because the average includes forty normal minutes and twenty slow minutes.
The last line gives the useful fact: the first 504 was at 22:40:00.
11:31 PM: one file, no install
Now the program had to run on web-03. The server runs Linux on x86-64. Shivam’s laptop could build a program for that server directly:
$ zig build-exe -O ReleaseFast -fstrip -target x86_64-linux-musl logscan.zig
$ ls -l logscan
-rwxr-xr-x 1 shivam shivam 273624 Oct 3 23:31 logscan
$ file logscan
logscan: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped
-target gives the machine for the build: x86-64, Linux.
This program does not use a C library at all. The Zig standard library makes calls to the Linux kernel directly.
Thus the result is “statically linked”: the file needs nothing else on the server. The server does not need a runtime, shared libraries or a package.
The file was 274 KB. Shivam copied the file to the server.
$ scp logscan web-03:/tmp/
11:33 PM: the real file
$ /usr/bin/time -f "%e s, %M KB" /tmp/logscan /var/log/shop/access.log
read 50000000 lines, 2075125000 bytes, through a 65536-byte buffer
skipped 51000 lines we could not parse
status requests
200 48471000
404 934000
504 544000
endpoint requests avg ms max ms
/api/checkout 9996000 699 5000
/api/search 9970000 89 119
/api/cart 9912000 59 79
/login 10115000 37 49
/ 9956000 17 23
first 504 at 2026-10-03T22:40:00Z
6.45 s, 652 KB
The program read fifty million lines in about seven seconds. The full process used 652 KB of memory.
Shivam also ran awk on the same file, to compare. The awk command counted only the status codes, and it took about 13 seconds.
11:36 PM
Shivam put the report in the incident channel.
Only checkout is slow. Everything else is normal. First timeout at 22:40:00. What shipped around 22:40?
Two minutes later, Urvashi replied.
Payments team changed the timeout config for the card provider at 22:39.
The payments team reverted the change at 11:41 PM. At 11:52 PM, the checkout error rate was zero again.
The next morning
Shivam added logscan.zig to the tools repository of the team. The program is about 220 lines.
Each person on the team can build the program for any server with one command. This also works for the ARM machines:
$ zig build-exe -O ReleaseFast -fstrip -target aarch64-linux-musl logscan.zig
Try it yourself
The full program is above the Run button.
- Press Copy.
- Save the program as
logscan.zig. - If you do not have Zig, install Zig.
- Run one of these commands:
$ zig run logscan.zig # writes access.log and scans it
$ zig run logscan.zig -- /path/to/your.log
Your own log will have a different format. Change parseLine for that format. The other code stays the same.
These chapters give more detail about each part:
- Read line by line. This chapter also shows lines that are longer than the buffer.
- Hash maps. This chapter also shows who owns the keys.
- Cross-compilation. This chapter shows how to build for a different machine.
About the numbers
Shivam, Urvashi and web-03 are not real. The numbers are real.
The 2 GB file is 1,000 copies of the sample log. Each time and size in this post is a measurement from a laptop with an Intel Core i5-1235U. The measurements used the Zig version at the top of this post.
In three runs, logscan took between 6.4 and 8.2 seconds. The memory of logscan stayed at 652 KB in each run. The output above is from the fastest run.
The awk command was awk '{c[$4]++} END{for(k in c) print k, c[k]}'. This command counts status codes and does nothing else.