TL;DR

  • At startup the daemon reads about 8,000 JSON records. I added a cache that reuses their bytes without opening them when the stat matches.
  • A same-size rewrite within one timestamp tick leaves the stat identical. Only files whose ctime is at least two seconds old enter the cache.
  • After an EC2 stop/start, the same EBS volume came back with a different st_dev and every entry missed. ext4 derives f_fsid from the on-disk UUID, so st_dev is rebound only when that value matches.

On a stopped EC2 host, two seconds of startup went to JSON reads

The daemon that runs agents reads every past execution record at startup. That is about 8,000 JSON files.

A restart on the same version finishes this in 165 ms. After the EC2 host was stopped and started, it took 1990 ms, because the page cache was empty.

I wanted a stopped host to start work within 20 seconds of the wake request, so these two seconds had to go.

Picking a way to avoid opening the files

There were three options.

  • Merge the records into one file. That changes the authoritative format and forces a rewrite of recovery and corruption quarantine.
  • Load lazily. Startup recovery has to look at every record, so it cannot be deferred.
  • Save the bytes read last time in a side file and reuse them when the stat matches. The authoritative files stay as they are. If the cache breaks, an ordinary read still works.

I picked the third. Git’s index uses the same idea: it records lstat results and uses them to decide whether working-tree files changed.

For each path the cache stores the stat fields, the bytes, and their SHA-256.

type recordStamp struct {
	Device, Inode, Owner, Group uint64
	Size, Modified, Changed     int64 // Modified = mtime, Changed = ctime
	Mode                        uint32
}

The cache file itself is used only if it is mode 0600, owned by the current user, and at most 128 MiB. If any check fails, the daemon reads the records normally.

CI got the old bytes of a record it had just rewritten

The first version failed in CI. A record was rewritten, and the cache still returned the old bytes.

The cause was timestamp granularity. Linux mtime and ctime carry nanosecond fields, but their values advance with the kernel’s coarse clock. A same-size rewrite within one tick leaves inode, size, mtime and ctime unchanged. Reusing a deleted file’s inode number has the same effect.

Git calls this “racy git”. Its fix treats entries modified at or after the index file’s own mtime as suspect and compares their contents again.

I chose something simpler. Only files whose ctime is at least two seconds old enter the cache. The stat taken before and after the read, on the same file descriptor, must also match.

before, _ := f.Stat()
data, _ := io.ReadAll(f)
after, _ := f.Stat()
first, last := fingerprint(before), fingerprint(after)
if first == last && time.Since(time.Unix(0, last.Changed)) >= 2*time.Second {
	cache[path] = cachedRecord{Stamp: first, Digest: sha256.Sum256(data), Data: data}
}

Recently changed files are read normally on the next startup too. Almost every record read at startup is hours old, so very few entries miss because of this rule.

The rule uses ctime rather than mtime because mtime can be set back with touch -r or os.Chtimes. ctime cannot be set by a user. Rewriting a file and restoring its mtime still changes ctime, so the cache misses.

The cache is also limited to ext4, XFS, btrfs, overlayfs and macOS APFS. Anything else is read normally.

After an EC2 stop/start, all 8,270 entries missed

The next problem showed up on a staging EC2 host. After a stop and start, none of the 8,270 valid entries were used, and loading took 2.89 seconds.

st_dev had changed from 66309 to 66305, which is 259:5 to 259:1 as major:minor. EBS volumes appear as NVMe devices, and their numbers follow the order in which devices answer at boot. AWS documents that device names can change between starts. The volume was the same.

There were three options.

  • Stop comparing st_dev. Git does this by default, because st_dev is unstable on network filesystems. It leaves room for a different volume mounted at the same path to match on inode and ctime by chance.
  • Match on the EBS volume ID. Getting from a path to a volume ID means walking the mount table and block devices, which is too heavy for a cache check.
  • Match on statfs f_fsid. ext4 derives it from the on-disk UUID: the kernel’s ext4_statfs returns uuid_to_fsid(es->s_uuid). The value stays the same for the same filesystem even when the device number changes.

I picked the third. The cache stores the root’s st_dev, filesystem type and f_fsid. At startup it compares them with the current values and rebinds only on ext4 with a matching f_fsid.

func rebind(old, cur volume, records map[string]cachedRecord) map[string]cachedRecord {
	if old == cur {
		return records
	}
	if old.Kind != "ext4" || cur.Kind != "ext4" || old.ID == ([2]int32{}) || old.ID != cur.ID {
		return nil // read normally
	}
	out := make(map[string]cachedRecord, len(records))
	for p, r := range records {
		if r.Stamp.Device == old.Device { // only entries from the previous root volume
			r.Stamp.Device = cur.Device
			out[p] = r
		}
	}
	return out
}

After rebinding, the inode, ctime, owner, mode and size checks all still apply. A volume restored from a snapshot has the same UUID, so f_fsid alone cannot tell the copy from the original. Filesystems other than ext4 still require the original st_dev.

What the stat cache rules out

When stat decides whether to trust cached bytes, the first question is what can match by accident, not what to compare. ctime age rules out same-tick rewrites. f_fsid rules out a renumbered device.

The cache never becomes the source of truth. On a miss the daemon reads the file, and recovery and quarantine run exactly as before.