# Ardor Institute (/work/ardor-institute)

<Callout type="warn" title="Status">
A working product, built and run end to end as a test case in April 2026, and not maintained now. The public site and the heat map are live, and the operator dashboard is open as a [demo](https://ardor.institute/demo): the real pages over sample data, with no sign-in. The hosted database has been retired, so payments and PDF generation are switched off and a report cannot be bought.
</Callout>

| Role | Year | Kind | Try it |
| --- | --- | --- | --- |
| Solo: product, design, engineering | 2025 to 2026 | Climate, marketplace | [ardor.institute](https://ardor.institute) |

| | |
| --- | --- |
| **€299** | per site, fixed price |
| **100+ and 10** | data centres and heat networks on the map, in ten countries |
| **31 Mar 2027** | the next reporting deadline in Germany |

## The problem [#the-problem]

Germany's Energy Efficiency Act makes every data centre above a size threshold file an annual waste-heat report with BAFA, the federal energy-efficiency office.

There are directories of European data centres, and none of them include thermal profiles: how much heat, at what temperature, how reliably, and whether the operator would connect to a district heating network. You can find out where data centres are. You cannot find out what heat they produce.

The filing contains exactly that data. An operator has to produce it anyway, and a district heating utility needs it to decide whether to lay pipe. Today it goes into a national archive nobody searches. France, the Netherlands and Ireland are building the same thing independently, in different formats and languages.

## What I built [#what-i-built]

- **Heat map.** A public map of data centres and district heating networks. Estimated profiles and report-backed profiles are labelled differently, because they are not the same thing.
- **Report wizard.** Three steps. Pick a facility on the map and the wizard pre-fills; otherwise enter IT load, efficiency, cooling type and location.
- **Calculation model.** Annual recoverable heat from four inputs, conservative by default, with a path for measured values. The method is published in full.
- **Checkout and delivery.** Payment, then a rendered PDF in the operator's dashboard, with a 30-day read-only link to send to a consultant.
- **Regulatory layer.** A German and English site, a glossary of 14 regulatory terms, guides to the 2027 obligation, and a consultation paper proposing a German register for tradable waste-heat certificates.

## How it is structured [#how-it-is-structured]

<Mermaid caption="One document serves two sides. The buyer side is planned, not built." chart={`flowchart LR
  O[Data-centre operator] --> W[Report wizard<br/>3 steps]
  W --> M[Calculation model<br/>IT load, PUE, cooling type]
  M --> P[Fixed-price report]
  P --> F[Filing with the regulator]
  P --> D[(Verified heat profile)]
  D --> H[Public heat map]
  D -.->|planned 2027 pilot| B[Heat buyers<br/>district heating utilities]
`} />

## In the code [#in-the-code]

<Callout type="info" title="Private repository">
These are short excerpts from `Beach-Bum/Ardor`, which is private.
</Callout>

<Files>
  <Folder name="src" defaultOpen>
    <Folder name="app">
      <Folder name="api">
        <Folder name="generate-report">
          <File name="route.ts" />
        </Folder>
        <Folder name="stripe">
          <Folder name="webhook">
            <File name="route.ts" />
          </Folder>
        </Folder>
      </Folder>
    </Folder>
    <Folder name="lib">
      <File name="heat-profile.ts" />
      <File name="feasibility.ts" />
    </Folder>
  </Folder>
  <Folder name="supabase" defaultOpen>
    <File name="schema.sql" />
    <Folder name="migrations">
      <File name="20260420100000_stripe_hardening.sql" />
      <File name="20260420110000_fix_rls_recursion.sql" />
    </Folder>
  </Folder>
</Files>

**One report, generated once.** Two things can ask for the same PDF at the same moment: Stripe's payment call and the page the customer is watching. The status column is used as a lock. The update only succeeds if the row is still waiting, so exactly one caller gets the row back and the other is told who owns it.

```ts title="src/app/api/generate-report/route.ts"
// Atomic status flip: only transition queued/failed → generating if the row
// is still in that state. If another concurrent invocation already claimed
// it (webhook retry + page-polling trigger firing at the same time, etc.),
// .select() returns no rows and we early-exit. This is the C3 fix from the
// payments/stripe-hardening audit.
const { data: claimed, error: claimErr } = await supabase
  .from("reports")
  .update({ status: "generating", error_message: null })
  .eq("report_id", body.reportId)
  .in("status", ["queued", "failed"])
  .select("*")
  .maybeSingle<ReportRow>();

if (claimErr) {
  return NextResponse.json(
    { error: "claim_failed", message: claimErr.message },
    { status: 500 },
  );
}
if (!claimed) {
  // Either the report doesn't exist, or it's in a non-claimable state.
  // Fetch current state so the caller gets useful info.
  const { data: current } = await supabase
    .from("reports")
    .select("status, pdf_blob_url")
    .eq("report_id", body.reportId)
    .maybeSingle<Pick<ReportRow, "status" | "pdf_blob_url">>();
  if (!current) {
    return NextResponse.json({ error: "report_not_found" }, { status: 404 });
  }
  if (current.status === "ready") {
    // Idempotent: another invocation already completed generation.
    return NextResponse.json({ ok: true, url: current.pdf_blob_url });
  }
  // generating / pending_payment — another invocation owns it.
  return NextResponse.json(
    { error: "invalid_state", status: current.status },
    { status: 409 },
  );
}
```

**A free-report invite, claimed once.** The invite row is locked for the length of the transaction, so two people opening the same link cannot both claim it, and the same person opening it twice gets the same report back.

```sql title="supabase/schema.sql"
declare
  v_invite outreach_invites%rowtype;
  v_report_id text;
  v_suffix text := '';
  v_alphabet text := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
begin
  -- Lock the invite row for update (prevents race conditions)
  select * into v_invite
  from outreach_invites
  where token = p_token
  for update;

  if not found then
    raise exception 'INVITE_NOT_FOUND';
  end if;

  if v_invite.expires_at < now() then
    raise exception 'INVITE_EXPIRED';
  end if;

  if v_invite.claimed_by is not null then
    if v_invite.claimed_by = p_user_id then
      -- Already claimed by same user, return existing report_id
      return v_invite.report_id;
    else
      raise exception 'INVITE_ALREADY_CLAIMED';
    end if;
  end if;

```

What a reviewer would say about these two. The first has no time limit on "generating", so a render that dies leaves the row stuck until someone resets it. The second lives in the schema file and not in a migration.

**A payment call, handled once.** Stripe delivers each event at least once, sometimes twice at the same moment. The whole decision is one statement, so two deliveries cannot both be told to go ahead. It also has to let a delivery through after an attempt that failed, or one that crashed and never finished; otherwise one bad attempt would block a payment for ever.

```sql title="supabase/migrations/20261112000000_access_and_payment_hardening.sql"
-- ── 4. Recognising a repeated Stripe call ──
--
-- Stripe delivers an event at least once. The table for remembering events
-- has existed since 20260420100000; this is the statement that uses it.
--
-- Returns true when the caller now owns the event and should handle it:
--   - first delivery
--   - a delivery after an attempt that ended in error
--   - a delivery after an attempt that never finished (crashed mid-handler)
-- Returns false when the event was handled, or is being handled right now.
--
-- One statement, so two deliveries arriving together cannot both get true.
create or replace function public.claim_stripe_event(
  p_event_id text,
  p_event_type text,
  p_report_id text default null
) returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
  v_claimed boolean;
begin
  insert into public.stripe_webhook_events (event_id, event_type, report_id)
  values (p_event_id, p_event_type, p_report_id)
  on conflict (event_id) do update
    set received_at = now(),
        handler_status = null,
        handler_error = null
    where stripe_webhook_events.handler_status = 'error'
       or (stripe_webhook_events.handler_status is null
           and stripe_webhook_events.received_at < now() - interval '5 minutes')
  returning true into v_claimed;

  return coalesce(v_claimed, false);
end;
$$;
```

**And the test that walks a report through every state.** These are the two statements the payment handler and the generator run, called in the orders that go wrong in production: twice, at the same time, late, and after the report is finished.

```sql title="supabase/tests/access_and_payments.sql"
-- ── 5. A report is queued once and generated once ──
-- These are the two statements the payment handler and the generator run
-- (src/app/api/stripe/webhook/route.ts, src/app/api/generate-report/route.ts).
UPDATE public.reports SET status = 'pending_payment';
CREATE FUNCTION t.rid() RETURNS text LANGUAGE sql AS $$ SELECT report_id FROM public.reports LIMIT 1 $$;

CREATE FUNCTION t.queue_paid() RETURNS text LANGUAGE sql AS $$
  SELECT t.run('service_role', NULL, format(
    $q$update public.reports set status = 'queued' where report_id = %L and status = 'pending_payment'$q$, t.rid()))
$$;
CREATE FUNCTION t.claim_generation() RETURNS text LANGUAGE sql AS $$
  SELECT t.run('service_role', NULL, format(
    $q$update public.reports set status = 'generating' where report_id = %L and status in ('queued', 'failed')$q$, t.rid()))
$$;

SELECT t.expect(t.queue_paid(),       'rows:1', 'payment moves a waiting report to queued');
SELECT t.expect(t.queue_paid(),       'rows:0', 'a repeated payment call changes nothing');
SELECT t.expect(t.claim_generation(), 'rows:1', 'the first generator claims the report');
SELECT t.expect(t.claim_generation(), 'rows:0', 'a second generator, arriving at the same time, gets nothing');
SELECT t.expect(t.queue_paid(),       'rows:0', 'a payment call arriving mid-generation does not reset it');
UPDATE public.reports SET status = 'ready';
SELECT t.expect(t.queue_paid(),       'rows:0', 'a payment call for a finished report does not regenerate it');
SELECT t.expect(t.claim_generation(), 'rows:0', 'and a finished report cannot be claimed for generation');
UPDATE public.reports SET status = 'failed';
SELECT t.expect(t.claim_generation(), 'rows:1', 'a failed report can be retried');
```

The test builds the schema in a throwaway local database and runs 36 checks as each kind of caller: signed out, signed in, and the server. They cover the payment path above, invites that can be claimed once and only by the server, and the rule that a person can only act for an organisation they belong to. That last one is a database trigger, so it holds for the browser, the API and the server alike.

## How a report gets made [#how-a-report-gets-made]

| Step | What happens |
| --- | --- |
| **1. The form** | The operator fills in three steps. The report is saved as "pending payment" with an id such as `ARD-20260418-K7QM`. |
| **2. Payment** | Stripe checkout. Stripe then calls the site, and the call's signature is verified before anything is believed. |
| **3. Generation** | The address is geocoded (limited to the twelve supported countries), the PDF is rendered by a separate service, stored, and emailed. The report moves through queued, generating, then ready or failed. |
| **4. Access** | Only the person who created a report can download it; a colleague in the same organisation cannot yet. A share link is a random 24-character token that expires after 30 days and can be withdrawn. |

Next.js 16 and React 19, Supabase for Postgres and sign-in, Stripe for payment, a separate PDF service, German and English throughout. 147 commits in April 2026.

## Data and access [#data-and-access]

Ten tables: people, organisations and their members, reports, the marketplace's records and matches, buyer accounts, Stripe's events, and a log of data requests. Row-level security is on for all ten. The Stripe event table has no access rules at all, which means only the server can read it.

The data-request log exists because the product handles personal data in the EU: each request under GDPR Articles 15 to 22 is recorded with its type, its 30-day deadline and what was done.

## The second half: the map and the marketplace [#the-second-half-the-map-and-the-marketplace]

Reporting is the part that was built to be bought. The part it exists to feed is the other half of the site: a map of where waste heat is, and a way for someone who needs heat to find it.

- **The map.** More than 100 data centres across ten countries and ten district-heating networks, as pins over a heat layer, with filters for capacity, cooling type and whether a site's figures are verified or estimated.
- **Feasibility, per buyer.** The same site is a good match for one buyer and a poor one for another. Each site gets a physical heat profile, and that profile is graded separately for four kinds of buyer: industry, district heating, hospitals and housing.
- **The marketplace records.** Tables for site profiles, buyer accounts, matches and the events on a match, so an introduction can be followed from first contact to outcome.

### How a match is graded [#how-a-match-is-graded]

A grade starts at 5 and moves on evidence, and it always says why.

| Evidence | Effect |
| --- | --- |
| Under 3 km from the buyer | +3, listed as a driver |
| Under 5 km | +2, listed as a driver |
| Under 10 km | +1 |
| Beyond the buyer's search radius | −2, listed as a blocker |
| Heat arrives at the temperature the buyer needs | up to +1.5, listed as a driver |
| Heat is too cool and needs a heat pump | flagged |

The result is one of three verdicts: feasible, borderline, not feasible, with its drivers and blockers attached.

### The roadmap [#the-roadmap]

| When | What | Status |
| --- | --- | --- |
| 2026 | Compliance reporting. Built and working end to end in April 2026. | On hold |
| 2026 – 27 | Map coverage and feasibility logic. A stronger map, better feasibility logic, and more report-backed profiles. | In development |
| After that | Buyer access and market coordination. Staged buyer access, partner routes, and later marketplace coordination built on reliable profiles. | Planned |

<Cards>
  <Card title="The operator dashboard, as a demo" href="https://ardor.institute/demo" description="Reports in every state, team and invites, marketplace opt-in. Sample data, no sign-in, nothing saved." label="Open ↗" />
  <Card title="The marketplace and its map" href="https://dev.ardor.institute/" description="111 data-centre heat profiles across ten countries, searchable on a map." label="Open ↗" />
  <Card title="The heat map product page" href="https://ardor.institute/en/products/heatmap/" label="Open ↗" />
  <Card title="Feasibility" href="https://ardor.institute/en/products/feasibility/" label="Open ↗" />
</Cards>

## What broke, and the fix [#what-broke-and-the-fix]

Checkout failed with `infinite recursion detected in policy for relation "org_members"`. A rule deciding who may insert a report looked up organisation members, and that lookup ran the rule again.

Two changes fixed it. The rules were rewritten to call small helper functions that read membership with the rules switched off for that one lookup. And checkout stopped depending on those rules: it verifies the person first, then writes the report as the server.

## What is not finished [#what-is-not-finished]

Things an engineer would find, so here they are.

- **Written, tested and never run live.** Repeated payment calls, refunds and disputes are handled in the change described above, which is merged. It is proven against a local database: the hosted one has been retired, and the demo takes no payments, so there is no live payment path to apply it to.
- **A migration that could not run.** Building the schema from scratch for the tests showed that the recursion fix below compared a role type with text and stopped there. The same change corrects it.
- **A stuck report stays stuck.** There is no time limit on "generating".
- **Rate limiting** is held in memory per server instance, so it does not hold across instances. The code says so and names the replacement.
- **No tests of the application code.** The 36 checks are on the database rules and statements. The pages and the PDF service have none.

## The decision that mattered [#the-decision-that-mattered]

I started with a marketplace thesis: compliance is the way in, the marketplace is the product. Every filing adds a verified heat profile, and buyers pay to search them.

Halfway through I rebuilt the site around a narrower claim: reporting first, market infrastructure later. A marketplace with an empty database helps nobody. Buyers need report-backed profiles, and those only exist once operators have filed.

The regulation does the hard part of a market: it forces supply to document itself. The product's job is to be the cheapest, clearest way to comply, and to keep the data.

## Open questions [#open-questions]

<Accordions type="single">
<Accordion title="Where it stands">

Built solo in April 2026 as an end-to-end test case: form, payment, generated report, delivery. It worked, and I am not maintaining it now. The site still shows where it got to, with the buyer marketplace planned as a 2027 pilot that depends on data quality.

</Accordion>
</Accordions>

## More [#more]

<Cards>
  <Card title="Project notes on the weblog" href="https://nedkarlovich.com/projects/ardor" />
  <Card title="Why I started thinking about waste heat" href="https://nedkarlovich.com/writing/why-i-started-thinking-about-waste-heat" />
</Cards>
