Skip to main content
Kill switches, counting every query, and the list of features I declined on purpose.

Creating a ColdFusion Calendar That Doesn’t Lie About Time - Part 5: Running It, and Knowing What Not to Build

Kill switches, counting every query, and the list of features I declined on purpose.

Four parts of this series were about building the calendar. This one is about what happens after the build is done, which is where I've learned most of what I know and where most of my confident statements went to die.

I'll cover how I decided it was ready, how I stop it in an emergency, how I know a scheduled task actually ran, how I count every query a page makes, and what I decided not to build. Every one of those has a story where the system told me something comforting and the system was wrong.

How I decided it was ready

I'd love to tell you there was a moment of triumph. There was a spreadsheet and a lot of disappointment.

The readiness document has one canonical section, and its heading ends with the words THIS SECTION WINS. Older sections stay as dated history with a note pointing at the section that supersedes them. I don't rewrite history. I add a floor above it and say which one to believe.

The real method was simpler than it sounds: I stopped reading the code and drove the real production UI. Here's the sequence of verdicts, because it's more honest than the headline:

  • First review: NO-GO, score 6 out of 10. Five defects reproduced in production, four of them material. One was a headline feature that, in the document's words, "has never worked at all."
  • Second review: NO-GO, 8.9. No defects this time. One authenticated journey family had never been exercised in production, the member subscription lifecycle.
  • Third review: GO, 9.4. Thirteen defects found and fixed across the exercise.

I'd like to dwell on the missing 0.6. The verdict doesn't say 10, and the document says why: a browser pass found two locale defects that no earlier review had recorded. One was a status column showing the raw word published in every language, because the template looked up the bare column value as though it were a translation key. The keys existed and were translated. Nobody had looked at the page in French.

The defects the specs hadn't found are the ones I'd put on a poster:

  • Editing any single occurrence of a series threw a 500, and the panel closed quietly so the change simply vanished (part two).
  • "Ends on" dropped the last occurrence (part one).
  • The reorder buttons did nothing, because the script that wired them ran before the <body> existed.
  • The Google Calendar subscription was named with a raw translation key, stored as tenant data.
  • The member dashboard died the moment a member subscribed, because a doubled hash sign inside a cfoutput handed cfloop the literal string.

My test suite was green for every one of those.

Five switches that aren't in the database

An emergency stop has three requirements. It must work when the database is the thing on fire. It must not need a deploy. And it must not itself be a query.

So the switches are in the process environment, not a table. There are five: inbound sync, public feeds, member feeds, reminder materialization, and delivery. The header comment explains the choices better than I can, so here it is:

 * WHY ENV AND NOT A TABLE. An emergency stop must work when the database is the
 * thing that is on fire, must not need a deploy, and must not itself be a query.
 * Rosterli's established configuration surface is env_service, read from the
 * node's environment file and rotated by the deployment scripts, which is
 * exactly the property an emergency control needs. It is per-node by
 * construction: an operator sets it on every node, and until they have, the
 * fleet is honestly reported as PARTIAL rather than pretending to be converged.

The detail I'd have you steal is the direction of failure. Look at what a garbled value does:

if ( !len( raw ) ) {
    return { engaged: false, state: "running", configured: false, value_length: 0 };
}

var token = lCase( raw );
if ( listFindNoCase( variables.TRUE_TOKENS, token ) ) {
    return { engaged: true, state: "stopped", configured: true, value_length: len( raw ) };
}
if ( listFindNoCase( variables.FALSE_TOKENS, token ) ) {
    return { engaged: false, state: "running", configured: true, value_length: len( raw ) };
}

// See the header: an unrecognized kill-switch value engages the switch.
return { engaged: true, state: "stopped_invalid_config", configured: true, value_length: len( raw ) };

Blank means not engaged, because absence of configuration must never take the product down. A recognized true engages it. A recognized false disengages it. And anything else engages it, which is the opposite of how every other boolean in the platform behaves. The header's reasoning is a single scenario: an operator types ture during an incident and believes delivery has stopped. "Treating that as 'keep sending' is how a leak becomes a mass mailing."

A switch that enables a feature should fail toward "off". A switch that stops something should fail toward "stopped". They're the same typo with opposite consequences, and the code is allowed to be inconsistent about it because the consequences are.

Two more details. The delivery switch is checked before claiming jobs:

// ── Emergency stop (Phase 9) ───────────────────────────────────────
// BEFORE claiming, deliberately. Claiming and then refusing would
// park every due job under a lease that has to expire before another
// worker can touch it, so a switch meant to pause delivery would
// instead delay it by the lease window after being cleared. Nothing
// is claimed, nothing is marked, nothing is cancelled: due work stays
// due and drains normally the moment the switch is cleared.
if ( calendar_kill_switch_service.isEngaged( "delivery" ) ) {
    calendar_kill_switch_service.auditRefusal( "delivery", "drain" );
    counters.killed = true;
    // STILL a heartbeat. The scheduler fired and the application
    // answered; that is exactly what a heartbeat measures, and
    // suppressing it here would make an engaged kill switch look like a
    // dead scheduler and fire the wrong alert. The switch has its own,
    // which stays firing for as long as it is engaged.
    calendar_heartbeat_service.markSuccess(
        task_key = "calendar_notification_drain",
        duration_ms = getTickCount() - started_at,
        counters = counters
    );
    return counters;
}

And the feed switches answer 503 with a Retry-After, never a 404, because a client that sees a persistent 404 concludes the calendar was deleted and may drop the subscription.

Now the confession. The comment says an operator can "undo in seconds." The switch lives in the process environment, which a running JVM can't change. Engaging or clearing one means rotating the environment file and restarting the engine on each node. That's not seconds. It's a deploy-shaped operation without the deploy. The design is still right, since it works with the database down and needs no code change, but the sentence in the header is more optimistic than the mechanism. I also have to report that I have no record of a production switch ever being engaged. The wiring is proven in specs and in an isolated probe engine, which is a different thing from having pulled the lever.

Proof that the scheduler ran

I had a monitoring problem that sounds trivial. How do I know a scheduled task is running?

"Nothing is due" is the normal state for a reminder drain. A healthy scheduler with an empty outbox and a scheduler that died three days ago produce identical dashboards. Activity-based monitoring can't tell them apart.

So each task writes a heartbeat. One row per task, updated in place. It never grows, so it never needs retention:

CREATE TABLE IF NOT EXISTS public.calendar_operations_heartbeat (
	task_key varchar(60) NOT NULL,

	last_start_utc timestamp with time zone,
	last_success_utc timestamp with time zone,
	last_failure_utc timestamp with time zone,

	-- 'ok' | 'failed' | 'running'. Application vocabulary; deliberately not a
	-- CHECK constraint, so adding a state later is not a migration.
	last_status varchar(20),
	last_detail_code varchar(60),
	last_duration_ms integer,

	-- Bounded integer counters only. Never content, never an identifier.
	last_counters jsonb,

	-- 'primary' | 'secondary'. The fleet ROLE, not a hostname: an alert that
	-- names an instance id leaks infrastructure into a notification channel.
	node_label varchar(20),

	-- ...

The database is the clock; the application never writes a now() of its own. A task that has never run reports ever_ran: false and stale: true. The heartbeat stores a fixed vocabulary, a stable detail code, and a handful of integers. It stores no message text, because an exception message is where somebody's email address ends up in a log.

I want to be straight about its record. As far as my notes show, it has never caught a real dead scheduler. What it has done is close a visibility gap, and prevent one false page: it would have paged "scheduler missing" about an hour after a deployment that had deliberately turned a task off. Both of those are real, and neither is a trophy.

The elvis operator reported a healthy sweep as stale

The most expensive line of ColdFusion I wrote on this project is one I'd tell you is correct:

// NOT `beat.stale ?: true`. On ACF the elvis operator returns the
// DEFAULT when the left side is boolean false, so a healthy sweep
// (stale = false) was reported as stale = true. That is what filled
// #alerts with calendar_retention_stale every five minutes while the
// sweep was succeeding hourly. Elvis is only safe here for values
// that can never legitimately BE false.
stale: ( structKeyExists( beat, "stale" ) ? beat.stale : true ),

false ?: true is true. I've confirmed it on the engine and it's in Adobe's documentation: the operator returns the right-hand side when the left is false, not only when it's null. I'd used it to supply a default for "no value", which is a perfectly reasonable thing to want, and it turned every healthy answer into an alarm. It "bit twice": once in the snapshot, once in the alert line.

The monitor that was shipped by nothing

There's a script that polls each node every five minutes and posts firing and recovery messages to Slack. It was tracked in the repository. It had a test. It had documentation. And the installer script didn't install it. It was absent from the Staging machine and from both production machines. The cron installer, for its part, removed every existing run_monitor.sh line before writing its own, so the documented workaround ("add it by hand") would have been erased by the next release, "with no symptom except Calendar alerts that stopped arriving."

Then I discovered that the check meant to catch deployment-hook mistakes had a regex that never matched the format the hooks were written in. It had been "validating zero hooks for as long as it existed." Fixing it immediately found five hooks that weren't executable.

And the alerts keyed on a "primary node" environment variable that appeared nowhere else in the repository and was unset on every machine. Both nodes computed the fleet alerts, logged them, "and sent nothing." At that time ten of fourteen alerts were silently dropped. A monitoring system that can't tell you it's blind is a decoration.

I now have a rule in the operations code: blindness is its own alert. If the mail directory can't be read, that's a warning on its own, because "zero dead letters" and "couldn't look" are different answers that used to render identically.

Retention is a re-delivery bug with a delay fuse

Part four told the story of the identity ledger. Here's the operational half.

Retention deletes old jobs, sync logs and revoked tokens, hourly, on the primary node only, in batches. It's also meant to delete approved change snapshots after a year. I'll come back to that one. The rule I'd put on a wall is the order: spend the identity first, then delete the job.

INSERT INTO public.calendar_notification_identity (
	identity_key, job_kind, state, spent_utc,
	group_id, organization_id, calendar_event_id, recipient_user_id
)
SELECT DISTINCT ON ( k.identity_key )
	k.identity_key, j.job_kind, 'spent', now(),
	j.group_id, j.organization_id, j.calendar_event_id, j.recipient_user_id
FROM public.calendar_notification_job j
LEFT JOIN public.calendar_change_notification c
       ON c.id = j.change_notification_id
CROSS JOIN LATERAL (
	SELECT public.calendar_notification_identity_key(
		j.job_kind, j.reminder_rule_id, j.calendar_event_id,
		j.occurrence_key, j.channel, j.recipient_user_id,
		COALESCE( c.idempotency_key, 'snap:' || j.change_notification_id::text )
	) AS identity_key
) k
WHERE CAST(j.id AS text) IN (:ids)
  AND k.identity_key IS NOT NULL
ORDER BY k.identity_key
ON CONFLICT ( identity_key ) DO UPDATE
	SET state = 'spent',
	    spent_utc = COALESCE( public.calendar_notification_identity.spent_utc, EXCLUDED.spent_utc );

(That's the statement as it sits inside the service's call, with its :ids parameter.) If the process dies after this and before the delete, the identity is spent and the job still exists. That's safe. The reverse order is the one that sends a message twice. Two smaller disciplines came out of it. A dry run doesn't write a heartbeat, because a click in an admin page must not hide a dead scheduler for another interval. And the identity ledger and tombstones are never pruned, because the ledger is the safety record. They hold a pseudonymous user id, so they're classified as personal data and leave only by tenant purge, which is a conversation for another series.

Counting every query

This is the part of the series I'm proudest of and least able to make sound interesting.

When I first audited the calendar, I asked a boring question: how many database queries does the calendar page make? Nothing in the product could answer. The one tool I had was called a statement counter, it claimed "real execution-scoped statement counting," and it was reading PostgreSQL's per-table scan statistics. It had never counted statements. Three queries that touch no table read as zero. One correlated subquery read as thirteen. I renamed it to say what it measures, and I built the real thing.

The real thing is a boundary. There is exactly one place in admin_app and shared that is allowed to call ColdFusion's queryExecute(), and everything else calls a wrapper that brackets it:

var query_options = structKeyExists( arguments, "options" ) ? structCopy( arguments.options ) : {};
var caching_requested = structKeyExists( query_options, "cachedWithin" ) || structKeyExists( query_options, "cachedAfter" );
query_options.result = "local.query_result_metadata";

var clock = meter.clock;
var started_nanoseconds = clock.nanoTime();
try {
    if ( structKeyExists( arguments, "params" ) ) {
        local.query_result_value = queryExecute( arguments.sql, arguments.params, query_options );
    } else {
        local.query_result_value = queryExecute( sql = arguments.sql, options = query_options );
    }
} catch ( any query_error ) {
    meter.recordFailure( clock.nanoTime() - started_nanoseconds, query_error );
    rethrow;
}
var elapsed_nanoseconds = clock.nanoTime() - started_nanoseconds;

// The shape, as recordExecution() takes it: 0 no result set (null),
// 1 a query, 2 an array, 3 anything else.
var kind = 0;
var rows = 0;
if ( !isNull( local.query_result_value ) ) {
    if ( isQuery( local.query_result_value ) ) {
        kind = 1;
        rows = local.query_result_value.recordCount;
    } else if ( isArray( local.query_result_value ) ) {
        kind = 2;
        rows = arrayLen( local.query_result_value );
    } else {
        kind = 3;
    }
}
meter.recordExecution(
    elapsed_nanoseconds,
    kind,
    rows,
    structKeyExists( local, "query_result_metadata" ) ? local.query_result_metadata : {},
    caching_requested
);

A per-request meter, kept in the request scope and never in a singleton, counts every execution, and a single log line per measured request reports the total. There's a fixed set of 22 route classes. A request that isn't exactly one of those routed events emits nothing and its meter is dropped immediately. The label can't be built from a URL, a tenant, a token or a piece of SQL.

The exactness comes from the boundary, and the boundary only holds because the build fails if it doesn't:

RAW_CALL = re.compile(r"(?<![\w.$])queryexecute\s*\(", re.I)
DOTTED_CALL = re.compile(r"\.\s*queryexecute\s*\(", re.I)
METERED_CALL = re.compile(r"(?<![\w.$])(meteredqueryexecutewithresult|meteredqueryexecute)\s*\(", re.I)
def rule_raw_calls(files):
    hits = []
    for relative_path, text in files.items():
        if relative_path == MIXIN:
            continue
        mask = code_mask(relative_path, text)
        for pattern in (RAW_CALL, DOTTED_CALL):
            for match in pattern.finditer(text):
                if mask[match.start()]:
                    hits.append("%s:%d" % (relative_path, line_of(text, match.start())))
    return hits

The checker's own header explains why this isn't a convention: "A convention would rot the first time somebody pasted a queryExecute() into a new service, and the count would silently become 'most executions'." It has twelve rules, including one I especially like: a SQL string holds one statement.

def rule_multi_statement(files):
    """L. One string, one statement.

    Measured on the pinned engine: for a queryExecute() string holding several
    statements Adobe ColdFusion reports ONE statement's update count (two
    UPDATEs of 3 and 2 rows report 3), so the affected-row figure for such a
    call would be silently wrong. Every string literal in the domain is read -
    not only a call's own argument - so SQL assembled into a variable first is
    covered too. A trailing semicolon is fine; a semicolon followed by another
    statement is not."""

Today the boundary has over 280 files and about 2,450 call sites behind it, and the check passes. I ran it again to be sure before writing that sentence.

What the count found

Once the numbers were exact, they found something no code review had. The same page, with two calendars and then with thirty:

  • The calendar index, the event feed and the editors: flat. Twenty-four executions at either size.
  • The group Reminders page: 18 executions with two calendars, 74 with thirty. Two queries per calendar.
  • The sidebar added one query per membership on every signed-in page.

That's an N+1, and I'd have bet money it wasn't there. It's the sort of defect a human reviewer can't see because every individual query looks reasonable. Pinned in a spec, then fixed: the Reminders page went from 74 executions to 13 and stayed flat. The spec's growth pin became a flatness pin: a page that reads per calendar again fails, and names itself.

The instrument had its own bar, declared before I measured: a median overhead of no more than the larger of 5% or 2 milliseconds. The first design failed it. It made five calls per execution and added roughly 2.9 and 2.1 milliseconds on the heaviest page. I rebuilt it to make one positional call per execution with the clock read inline, and it came in at about 1.2. The record keeps the failure. I mention it because the version of this story where the first design passes is the one you've read before.

A controller that went on a diet

The calendar controller was 3,752 lines, 91 functions and 29 injected dependencies. It had 27 routed actions and, I'm fairly sure, opinions.

I decomposed it in a specific order, and the order is the lesson: instrument first, characterize second, move third. The query counter existed before I touched a line. Then I wrote 52 characterization specs over real HTTP, five principals, both scopes, and made them pass against the unchanged controller. Only then did I move code, in eight independently revertable commits, re-reading the instrument after each. Thirty-seven of thirty-seven per-route database records came out identical after every commit. The refactor changed no query.

Today the controller is 1,383 lines, 48 functions and 13 injections, against ceilings of 1,400, 50 and 13. That's seventeen lines of headroom, and it's intentional. A ceiling you can't hit isn't a ceiling. The ownership is enforced by a check, not by goodwill:

def rule_controller_ownership(root):
    problems = []
    text = read(root, CONTROLLER)
    if text is None:
        return ["%s is missing" % CONTROLLER]
    code = strip_comments(text)
    declared = functions(code)
    for name in MOVED_FROM_CONTROLLER:
        if name in declared:
            problems.append("CONTROLLER_OWNERSHIP %s declares %s(), which Phase 4 moved out" % (CONTROLLER, name))
    for name in declared:
        if name not in CONTROLLER_KEEPS:
            problems.append("CONTROLLER_OWNERSHIP %s declares %s(), which is not on the list of what the thin controller keeps" % (CONTROLLER, name))
    if SQL.search(code):
        problems.append("CONTROLLER_OWNERSHIP %s runs SQL" % CONTROLLER)
    return problems
def rule_controller_size(root):
    text = read(root, CONTROLLER)
    if text is None:
        return []
    got = measure(text)
    problems = []
    for key, ceiling in CONTROLLER_CEILING.items():
        if got[key] > ceiling:
            problems.append("CONTROLLER_SIZE %s: %d %s, ceiling %d. Move the new work into the service that owns its family, or raise the ceiling in the same reviewed change and say why" % (CONTROLLER, got[key], key, ceiling))
    return problems

Read the last error message again. It doesn't say "no." It says move the work, or raise the ceiling in the same reviewed change and say why. Nobody gets stuck. They get an argument.

A check that lints my prose

One of my CI checks reads documents, not code. It fails the build if an active document describes my table-scan counter as an exact statement counter. It does that because I once wrote exactly that sentence in two phases of documentation:

 5. NOTHING DESCRIBES THE DATABASE WORK COUNTER AS AN EXACT STATEMENT COUNTER.
    `db_work_counter` reads pg_stat_xact_all_tables and reports SCANS. It was
    called `db_statement_counter` and claimed statement counting for two
    phases; the component and the operator view were corrected in Phase 10 and
    the launch document in Phase 1 of this audit.

I'm telling you this partly because it's useful, and partly because I'm about to admit that the same check didn't catch a number. The telemetry service has 22 route classes. My project instructions file, the one I give my AI tools, still says 18. It was 18 in the first commit; four classes were added later. The check validates that route labels named in documents are ones the code can emit. It doesn't check a count, so the count rotted in plain sight.

The code wins. I say that in the docs, in the instructions and in the handoff notes, and then I leave the evidence of the exception where you can find it.

What I decided not to build

A calendar that doesn't lie also has to be honest about its edges. Five things I've been asked for, or could reasonably be asked for, and decided against. I recorded each with its reasoning on the day, so I'd stop relitigating it.

Two-way sync. Writing changes back to Google or Outlook.

"Writing back to an external provider is a materially larger trust and security surface than the bounded, read-only fetch every Calendar decision since Phase 12 has been built around: provider OAuth, a write credential per tenant, and the provider's data as the target of Rosterli's writes. K3's whole point was containing untrusted inbound data; this would add trusted outbound writes."

I'd only revisit it alongside a deliberate security review, never as cleanup.

RSVP and attendance. Who's coming.

"Attendance is registration-side functionality: the Registration leg owns submissions, capacity, invitations and check-in (its R5), and a Calendar-side implementation would be a second, divergent copy of machinery Registration already owns well."

If I build it, it's its own scoped feature on Registration's patterns, with the calendar contributing the event and occurrence identity.

Providers beyond Google. Apple, Outlook, TeamSnap, SportsEngine.

"No customer or product requirement names another provider."

And the second half is the part I'd keep: widening the host set multiplies the surface of a bounded egress tool, "for a need that does not exist yet." The price of more providers is egress isolation and a per-host budget, and that price "is not paid for a hypothetical."

Organization-scope inbound feeds. Aggregating feeds across an organization.

"Aggregating feeds across an organization is a product expansion with no recorded demand, not a defect and not a gap."

Individual erasure. I'll be careful here, because this one has moved.

When I wrote the decision down on September 24, the answer was that it wasn't mine to decide: what Rosterli is obligated to provide "is a legal question before it is an engineering one," and nothing was built. That entry is now stale as a description of the platform. Privacy lifecycle work has arrived since, covering how erasure and retention work across everything, and it is its own subject. I'm leaving the original decision as I wrote it, dated, and not rewriting it to look prescient.

There's one more, which is a non-decision rather than a feature: no rendered-feed cache. A cache key correct enough to be safe has to include nearly everything the render already reads. A stale entry would be a privacy leak, not a slow page.

What it taught me

  • "Ready" is a claim about evidence. Write down which evidence, and which section wins.
  • Drive the real UI. My green test suite didn't know the Status column was in English.
  • An emergency stop is a design, not a boolean. Choose its failure direction on purpose, and write the restart cost down.
  • "Nothing is due" and "the scheduler is dead" look the same. Measure the thing that proves it ran.
  • A monitor that nothing installs is a decoration.
  • Don't use ?: for a default when the real value can be false.
  • If you want an exact count, make the only way to the database go through the counter, and make the build fail for everything else.
  • Do the characterization first. Then you can refactor without arguing.
  • A decision recorded with its reasoning is cheaper than the next meeting about it.
  • When a document and the code disagree, the code wins. Then go and fix the document.

Looking back

I started this series saying a calendar is the one feature where every user is a domain expert. I think the thing I'd say now is narrower. Time is the one thing everybody believes they understand, and the calendar is where that belief meets a database.

Every part came back to the same instinct. Store the instant and the zone. Make identity the original slot. Make the database refuse the nonsense. Refuse before you repair. Count instead of guess. And when the system says everything is fine, ask what it can't see.

The code will keep teaching me things. The 2:30 a.m. series that never comes back from 3:30 is the latest, and I found it by writing this series. That is, I think, the best argument I have for writing a series.

Go check your own recurrence loop at 2:30 in the morning.