> For the complete documentation index, see [llms.txt](https://docs.ipcheck.ing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ipcheck.ing/developer/architecture/ip-data-sources.md). Agents can also search and read this documentation through its [MCP server](https://docs.ipcheck.ing/~gitbook/mcp).

# IP Data Sources

How multiple IP geolocation sources are queried and normalized into one canonical shape.

Two questions drive most of MyIP, and they are answered by different machinery:

* **"What is my IP?"** — the browser asks several third-party echo endpoints directly. The backend is not involved.
* **"Where is this IP?"** — the browser asks *our* backend, which queries one geolocation provider (or a local database) and normalizes the answer.

Keeping them separate is deliberate: an echo endpoint must see the visitor's own connection, so it cannot be proxied.

```mermaid
flowchart TD
    subgraph Browser
      G["utils/getips/ — runChain() over one provider per source"]
      T["utils/ip/transform-ip-data.js"]
      C["IP cards"]
    end
    subgraph Backend
      H["Geolocation handlers in api/<br/>iplocate, ipapi-com, ipapi-is,<br/>ip2location-io, bigdatacloud, ipcheck-ing, maxmind"]
      M["server/datasets/maxmind-service.js — local mmdb"]
    end
    P["Third-party echo endpoints<br/>Cloudflare, IPCheck.ing, IPIP.net, ..."]
    U["Geolocation providers"]

    G -->|"direct fetch"| P
    G -->|"the IP"| H
    H --> U
    H --> M
    H -->|"canonical JSON"| T --> C
```

## Step 1 — resolving your own IP

`frontend/utils/getips/` holds one small module per source. Each exports a self-describing **provider object**:

```js
{ id: 'cloudflare-v4', name: 'Cloudflare IPv4', run: async (useJsonEndpoint) => '203.0.113.7' }
```

A provider's only job is to hit one upstream — through `fetchWithTimeout` (5-second browser default) — and resolve the raw IP string, or throw. It does not validate, and it does not know about any other provider.

Validation and fallback live one level up, in the `runChain()` runner exported by `frontend/utils/getips/index.js`. It walks its providers in order and returns the first hop whose answer passes `isValidIP()` from `common/valid-ip.js`, as `{ ip, source }` where `source` is the winning provider's display name. An exhausted chain resolves `{ ip: null, source }` carrying the last provider's name — the runner never throws.

`frontend/components/IpInfos.vue` renders up to six cards and assigns one chain to each, by index:

| Card | Primary source     | Endpoint                               | Falls back to                                   |
| ---- | ------------------ | -------------------------------------- | ----------------------------------------------- |
| 0    | IPCheck.ing IPv4   | `4.ipcheck.ing`                        | IPify IPv4 (`api4.ipify.org`)                   |
| 1    | IPCheck.ing IPv6   | `6.ipcheck.ing`                        | IPify IPv6 (`api6.ipify.org`)                   |
| 2    | Cloudflare IPv4    | `1.0.0.1/cdn-cgi/trace`                | MyExternalIP IPv4                               |
| 3    | Cloudflare IPv6    | `[2606:4700:4700::1111]/cdn-cgi/trace` | MyExternalIP IPv6                               |
| 4    | IPIP.net           | `myip.ipip.net/json`                   | Upai (`pubstatic.b0.upaiyun.com`)               |
| 5    | IPCheck.ing IPv6/4 | `64.ipcheck.ing`                       | — (JSON, then the same host's `/cdn-cgi/trace`) |

{% hint style="info" %}
The three IPCheck.ing sources take a `useJsonEndpoint` argument, which `IpInfos.vue` sets from `isUpstreamSite()` (`frontend/utils/upstream-site.js`): true only on ipcheck.ing's own hostnames. There they read the JSON endpoint; every other deployment reads the Cloudflare-style `/cdn-cgi/trace` text of the same host. If the JSON call fails they retry via trace before giving up.
{% endhint %}

Failure handling is layered:

1. **Inside a chain**, a provider that throws and a provider that answers with garbage are treated identically: `runChain()` logs a `console.warn` and advances to the next provider. A malformed answer does not end the chain — it only costs that one hop. If no provider produces a valid IP, the chain resolves `{ ip: null, source }`.
2. Every card runs its own resolve-then-detail pipeline, and all six run under `Promise.allSettled`, so a dead source cannot sink the batch. Cards paint independently as they land.
3. When a card's whole chain fails, the SPA emits an `ip-source:exhausted` event on the app bus. Sentry (when configured) captures it only if another card of the same IP version did resolve — otherwise "our chain failed" is indistinguishable from a visitor with no IPv6, which is routine noise.

Individual source failures are `console.warn` by design, so they never reach error monitoring; the per-card exhaustion event is the health signal.

## Step 2 — geolocating an IP

Once a card has an IP it calls the backend. `frontend/data/ip-databases.js` is the registry of selectable sources:

| id | Name           | Endpoint                                    | Needs a key                                                            | Extended fields |
| -- | -------------- | ------------------------------------------- | ---------------------------------------------------------------------- | --------------- |
| 0  | IPCheck.ing    | `/api/ipchecking?ip={{ip}}&lang={{lang}}`   | `IPCHECKING_API_KEY` + `IPCHECKING_API_ENDPOINT` (the IPCheck.ing API) | Yes             |
| 1  | IPAPI.is       | `/api/ipapiis?ip={{ip}}`                    | `IPAPIIS_API_KEY`                                                      | Yes             |
| 2  | IP2Location.io | `/api/ip2locationio?ip={{ip}}`              | `IP2LOCATION_API_KEY`                                                  | Yes             |
| 3  | IP-API.com     | `/api/ipapicom?ip={{ip}}&lang={{lang}}`     | No                                                                     | Yes             |
| 4  | BigDataCloud   | `/api/bigdatacloud?ip={{ip}}&lang={{lang}}` | `BIGDATACLOUD_API_KEY`                                                 | Yes             |
| 5  | IPLocate.io    | `/api/iplocate?ip={{ip}}`                   | `IPLOCATE_IO_API_KEY`                                                  | Yes             |
| 6  | MaxMind        | `/api/maxmind?ip={{ip}}&lang={{lang}}`      | Local database, no key at request time                                 | No              |

Each row also carries a `slug`, the route key in its endpoint (`ipapiis`, `maxmind`, …). It is the value of the `?ipdb=` URL parameter, which picks a source for one page load over the Preferences choice — see [Global URL parameters](https://docs.ipcheck.ing/developer/architecture/frontend.md#global-url-parameters).

The array order is both the Preferences list order and the order the fallback walk follows. Besides its endpoint, a row carries `configKey` (the `/api/configs` flag gating it — the flag of its row in `api/ip-sources.js` — absent for key-free sources), `extended: true` when the source's answer carries the `extended` block (see below), and `attribution: { url }`, the provider's home page, linked from the IP section's data-source sentence.

`buildDbUrl(db, ip, lang)` substitutes the `{{ip}}` and `{{lang}}` placeholders. `{{lang}}` is the locale registry's `apiTag` for the active UI locale rather than the UI code itself — the tag upstream databases localize place names by. No handler validates it; see [i18n](https://docs.ipcheck.ing/developer/development/i18n.md). Each source's `enabled` flag is derived from the `/api/configs` feature flags when they load (`applyConfigAvailability`) — key-gated sources follow their flag, key-free ones are always available — and runtime fetch failures never touch it. Users switch source in Preferences; if a stored choice points at a source that is no longer configured, it is migrated to the nearest available one (`nearestEnabledId`, walking forward in list order) with a toast — the only case where the stored preference is rewritten. Configuring keys is covered in [Optional API Keys](https://docs.ipcheck.ing/developer/configuration/optional-api-keys.md).

### Client-side fallback chain <a href="#client-side-fallback-chain" id="client-side-fallback-chain"></a>

`IpInfos.vue` does not simply query the preferred source and give up. Inside `fetchIPDetails()`:

* The requested source is looked up in the **enabled** list; if it is absent (its config flag is off, or configs have not loaded yet), the walk starts at the first enabled one.
* On an error it logs, advances to the next enabled source, and retries — until every enabled source has been attempted.
* Landing on a different source than requested shows a one-time toast and drifts the session's runtime source, so later queries start from the one that works — the stored preference is never rewritten.
* Results are cached per IP, and in-flight requests are deduplicated by IP, so six cards showing the same address produce one request.
* A source that has used up its daily limit (below) answers `429`, which the walk treats like any other error: the card moves on to the next source.

### Daily limits <a href="#daily-limits" id="daily-limits"></a>

[`IP_SOURCE_DAILY_LIMITS`](https://docs.ipcheck.ing/developer/reference/environment-variables.md) caps how many successful answers each geo route gives per day, as comma-separated `key=whole-number` pairs such as `ipapiis=90000,ip2locationio=50000`. The keys are the `key` of each row in `api/ip-sources.js`, which is also the route's last path segment: `iplocate`, `ipapicom`, `bigdatacloud`, `ipapiis`, `ip2locationio`, `maxmind`, `ipchecking`. `0`, or a source left out, is unlimited.

The `sourceDailyLimit(key)` middleware in `server/source-daily-limits.js`, which `backend-server.js` puts on every route it mounts from that registry, holds a slot for each request and gives it back when the answer is an error status or the connection is cut, so only successful answers count. An answer served from the edge cache never reaches the backend and is not counted. Past the ceiling the route answers `429 { "error": "...", "code": "source_daily_limit" }` until the server's local calendar day ends. The counts survive a restart in `common/source-limits-db/`; in Docker they survive a recreated container only when that directory is on a volume. Each backend process counts on its own, and a malformed pair is ignored with one warning at startup. This is a ceiling per source, not a per-visitor rate limit.

## The canonical response shape <a href="#canonical-response-shape" id="canonical-response-shape"></a>

Every geolocation handler returns the same JSON, whatever the upstream looked like. From `api/iplocate.js`, leaving out its optional `extended` block:

```js
{
    ip,
    city,
    region,
    country,        // ISO 3166-1 alpha-2
    country_name,
    country_code,   // same code as `country`
    latitude,
    longitude,
    timezone,       // "Asia/Singapore" — added by middleware, not the handler
    asn,            // "AS13335" — with the AS prefix
    org
}
```

| Field                      | Notes                                                                                              |
| -------------------------- | -------------------------------------------------------------------------------------------------- |
| `ip`                       | Echoed back by the upstream                                                                        |
| `city` / `region`          | Free-form strings; `'N/A'` or null when the upstream has nothing (which one depends on the source) |
| `country` / `country_code` | Both carry the ISO alpha-2 code                                                                    |
| `country_name`             | Upstream's own name — the frontend usually replaces it                                             |
| `latitude` / `longitude`   | Numbers                                                                                            |
| `timezone`                 | IANA zone name, `''` when the coordinates are unusable. See below                                  |
| `asn`                      | Normalized to the `AS<number>` form; sources returning a bare number get the prefix added          |
| `org`                      | Organization or ISP name                                                                           |

Any source may add an optional `extended` block; its field list and validator are in `common/ip-extended.js`. Who fills what:

| Source         | `extended` block                                                                                                                                         |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| IPAPI.is       | Line type, anonymizer yes / no, abuse activity yes / no, and the provider's `abuserScore` as a metric                                                    |
| IP2Location.io | Line type (from the usage type), anonymizer yes / no, abuse activity yes / no, and `fraudScore` out of 100 as a metric — whatever the key's plan returns |
| IP-API.com     | Line type (hosting or mobile only) and anonymizer yes / no; the handler asks the upstream for a named list of fields                                     |
| BigDataCloud   | Line type (hosting or mobile only), anonymizer yes / no, abuse activity yes / no                                                                         |
| IPLocate.io    | Line type (hosting, residential or business; no mobile signal), anonymizer yes / no, abuse activity yes / no                                             |
| IPCheck.ing    | Anonymity verdict with provider and protocol, line type, native flag, quality score with its details, abuse level, scenario friction, flags              |
| MaxMind        | None: basic location fields only                                                                                                                         |

The five provider handlers build their block with `buildExtended()` from `server/source-extended.js`, which drops a block that does not validate, so the base answer never depends on it. A yes / no is the code `detected` or `none`; a metric is the provider's own indicator, shown as plain text under its own name and never as the quality score. What the upstream does not return is simply absent.

`api/ipcheck-ing.js` sends the IPCheck.ing API's answer on with the geo fields plus the block built by `server/ipcheck-ing-extended.js`, and nothing else. When that API withholds the advanced fields — signed out, monthly quota used, or a cooldown — the block is just `{ "gate": "auth" | "quota" | "cooldown" }` and the card shows the matching prompt. That is not a failure: the response is still a `200` with full geo data, nothing errors, and no fallback source is tried.

### The advanced block <a href="#ipcheck-ing-advanced-block" id="ipcheck-ing-advanced-block"></a>

The card's detail area is `frontend/components/ip-infos/IpDetailPanel.vue`, a shell holding the metadata grid, the inline Map / Country-traffic panels and the dialogs. It renders two blocks of its own:

| Component             | What it renders                                                                                                                                                                                                                                                                                                                                                                                                             |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `IpAdvancedBlock.vue` | The card's extended fields, from whichever source answered, each hidden when the answer lacks it; a gated card shows one sign-in / quota / cooldown prompt instead. A source's metrics render as plain text under their own names. Below the fields sits one details frame that shows either `ScoreDetailsPanel.vue` or `ScenarioFrictionPanel.vue`, never both, when the answer carries score details or scenario friction |
| `IpAsnBlock.vue`      | The ASN row with its Info / History / Connectivity toggles. The history fetch is `loadAsnHistoryInto()` in `frontend/utils/ip/asn-history.js`, beside the other ASN loaders in `utils/ip/`                                                                                                                                                                                                                                  |

Abuse activity and scenario friction arrive ready-made in `extended`; the frontend only renders and records them. Scenario friction's display logic (validation, dot order, level → tone mapping) lives in `frontend/utils/ip/scenario-friction.js`, its copy in `ipInfos.scenarioFriction.*`. Their codes — abuse levels (`none` / `low` / `medium` / `high`, plus `detected` for a yes without a frequency), scenario ids, friction levels — are listed once in `common/codes/ip.js`; the abuse levels' labels are in `frontend/utils/codes/ip-labels.js`, the scenarios' in `scenario-friction.js`.

Both reach the ipinfo report section, differently. The abuse activity level is `abuseLevel`, an ordinary field: share links, the JSON download, the AI copy and `/r/:id` carry it. Scenario friction is `scenarios` (scenario id → level, never the reasons), a local-only field: Snapshot History keeps and compares it, and every shared output strips it — see [Report collector](https://docs.ipcheck.ing/developer/architecture/frontend.md#report-collector).

### `timezone` comes from the middleware, not the source <a href="#timezone-from-coordinates" id="timezone-from-coordinates"></a>

No handler produces `timezone`, and no upstream field is read for it. The `withTimeZone()` middleware (`server/ip-timezone.js`), attached to all seven geo routes, resolves the `latitude` / `longitude` already in the response to an IANA zone name and adds it on the way out — 2xx only, so error bodies never grow the field. Every route mounted from `api/ip-sources.js` carries it, so a new geo source inherits it; the pass-through proxy needs no upstream change.

Deriving it from the response's own coordinates is the whole point: asking a second database about the same IP would eventually place it elsewhere and print a zone contradicting the city beside it. Coordinates the source could not resolve (`'N/A'`, missing, or a point in open water) yield `''` rather than a guess — those payloads carry no city either, so the card omits both.

Only the zone name is sent. Geo routes sit behind a 24-hour edge cache, and a cached UTC offset would be an hour wrong for every visitor between a DST switch and the entry's expiry; the frontend renders the offset per view instead.

<details>

<summary>What the frontend does with the payload</summary>

`frontend/utils/ip/transform-ip-data.js` turns a canonical response into card data:

* `country_name` is re-derived from the country **code** locally so every source shows the same UI-language name; the upstream string is only a fallback.
* `country_code` of `'N/A'` becomes an empty string. The code doubles as the query key for the country activity heatmap (`/api/cfradar?view=country-traffic&country=`), and an empty code simply hides that entry point.
* `org` becomes `isp`, and an `asn` starting with `AS` gets an `asnlink` to bgp.tools.
* `timezone` passes through unchanged; the card pairs it with a UTC offset computed in the browser (`frontend/utils/time-utils.js`).
* Coordinates are rounded to one decimal for `mapUrl` / `mapUrl_dark`, which point at `/api/map`. At the map's zoom level \~0.176° is one pixel, so 0.1° is sub-pixel — the marker looks identical while every IP in the same grid cell collapses onto one edge-cache key. The full-precision coordinates are kept for display.
* It maps the `extended` block, from any source, to the card's advanced fields (a gated block yields only `extendedGate`) — see [The advanced block](#ipcheck-ing-advanced-block).
* It records the source that answered as `geoSourceId`.

</details>

Adding a source takes three pieces: an adapter in `api/` that produces this shape through `makeGeoHandler({ name, buildUrl, normalize })` (`server/geo-handler.js` owns the shared shell: read the already-validated `?ip`, fetch through `fetchUpstream`, throw on a non-2xx status — outage pages come back as HTML and would otherwise blow up `JSON.parse` — normalize, respond, and log-and-500 on failure); a row in `api/ip-sources.js`, from which the route and its middleware chain, the daily-limit key and the `/api/configs` flag all derive; and a row in `frontend/data/ip-databases.js`, which `tests/ip-sources.test.js` checks against the registry. If the provider reports more than location, the adapter adds an `extended` block through `buildExtended()`. The walkthrough is [Adding an IP Data Source](https://docs.ipcheck.ing/developer/development/adding-an-ip-data-source.md).

### The data-source sentence <a href="#data-source-sentence" id="data-source-sentence"></a>

The IP section's notes paragraph ends with one sentence naming the database that answered the cards — before any has, the one in effect: an `?ipdb=` override, else the Preferences choice — linked to its `attribution.url`, with an inline **change** link that opens Preferences at that setting (`frontend/components/ip-infos/IpSourceBlock.vue`, copy `ipInfos.sourceFields.sentence`). It is hidden in simple mode along with the notes; the cards themselves carry no data-source row.

## Local datasets

Three families of datasets live on disk inside `common/` — MaxMind GeoLite2, the CAIDA downloads and the IEEE MAC registries — and are read synchronously at request time. Each dataset is a row in `server/datasets/datasets.js`, kept current by one in-process engine, `server/datasets/dataset-updater.js` (see [Updating](#updating) below).

### MaxMind GeoLite2

`server/datasets/maxmind-service.js` opens `GeoLite2-City.mmdb` and `GeoLite2-ASN.mmdb` from `common/maxmind-db/` and keeps both readers in memory. `lookupMaxMind(ip, lang)` merges a City and an ASN record into the canonical shape, resolving localized names with an English then `'N/A'` fallback. If either reader is missing it throws with `statusCode` 503, and `/api/maxmind` answers 503 — the API degrades, the server still runs.

The same readers answer the Bulk IP Lookup tool (`POST /api/bulk-lookup`, up to 200 IPs per request). Its source is a row in `server/bulk-lookup-sources.js`, picked by [`BULK_LOOKUP_SOURCE`](https://docs.ipcheck.ing/developer/reference/environment-variables.md#bulk-lookup-source): `maxmind` is the default and, for now, the only row. A source there must be local data — one request carries 200 IPs, so it never calls a metered upstream. `getMaxMindBuild()` reports the loaded City database's build date, which the tool shows next to the source name.

The `maxmind` row is enabled only when `MAXMIND_ACCOUNT_ID` and `MAXMIND_LICENSE_KEY` are both set, and publishes City and ASN together as one set. Setup instructions live in [MaxMind Setup](https://docs.ipcheck.ing/developer/getting-started/maxmind-setup.md).

### CAIDA as2org, AS relationships and PeeringDB

Three more rows in `server/datasets/datasets.js` cover the CAIDA downloads:

| Dataset     | File                                       | Source                                                                                                                                 | Used by                                                                                                               |
| ----------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `as2org`    | `common/as-org-db/as-org2info.txt`         | `publicdata.caida.org/datasets/as-organizations/latest.as-org2info.txt.gz`                                                             | AS → organization name lookups                                                                                        |
| `as-rel`    | `common/as-rel-db/as-rel2.txt`             | Newest `*.as-rel2.txt.bz2` in `publicdata.caida.org/datasets/as-relationships/serial-2/`                                               | The AS connectivity graph and neighbour lists (`/api/asn-connectivity`, and the ASN Profile's `connectivity` section) |
| `peeringdb` | `common/peeringdb-db/peeringdb-index.json` | Newest `peeringdb_2_dump_YYYY_MM_DD.json` in `publicdata.caida.org/datasets/peeringdb/YYYY/MM/` (current month, else the previous one) | The `peeringdb` section of `/api/asn-profile`                                                                         |

`as2org` has a stable `latest` symlink upstream, so a `HEAD` plus `Last-Modified` is enough to detect a new snapshot. `as-rel` and `peeringdb` have none, so their rows scrape the directory listing and takes the lexicographically newest dated filename. The first two are decompressed on the fly; every dataset is validated before being published.

The `peeringdb` row carries one extra gate: it is skipped by both the boot download and the schedule unless `CLOUDFLARE_API_KEY` is set, because the ASN Profile — its only consumer — is not listed without that key.

`server/datasets/as-rel-db.js` parses the pipe-delimited rows and keeps the provider-to-customer (`-1`) and peer-to-peer (`0`) relationships — sibling rows are skipped — building a customer → providers index, a symmetric peers index and a customer count per AS. The Tier 1 set is derived from the snapshot rather than hardcoded: an AS with no providers in the p2c topology that also provides transit to at least 100 others. `/api/asn-connectivity` then does a fully local, synchronous BFS from the origin AS out to Tier 1s, emitting `transit` edges from the p2c index and `peering` edges where a network reaches the Tier 1 clique settlement-free — which is also what a Tier-1 origin's own graph consists of.

Relationship counts — the ASN Profile's neighbour lists — are computed by `server/as-relationships.js` with the same rule the graph walk uses: a network adjacent to enough Tier 1s has its non-Tier-1 "providers" treated as CAIDA misinference and left out, so the counts never show an upstream the graph drops.

`server/datasets/as-org-db.js` parses CAIDA's pipe-delimited TXT (\~12 MB) instead of the equivalent JSONL (\~28 MB) — identical content, and `split('|')` beats `JSON.parse` per line by roughly 40%. Both modules pick the newest matching file by modification time, so a manually downloaded snapshot with a different name still works. A file that parses to nothing counts as missing.

The PeeringDB dump is different in kind: CAIDA mirrors the full public PeeringDB export daily as one JSON document of roughly 116 MB, and only a fraction of it is needed. `server/datasets/peeringdb-distill.js` streams the download from the system temp directory and parses one row at a time from four tables (`net`, `ix`, `netixlan`, `netfac`), never the document as a whole; the contact (`poc`) and organization tables are skipped byte by byte and never stored. The result is a compact per-ASN index — network type, scope, traffic level, ratio, general peering policy, IRR as-set, website, and the exchanges and facilities the network is present at — published as `peeringdb-index.json` (about 6 MB); the raw dump is deleted afterwards. `server/datasets/peeringdb-db.js` loads that index into memory at startup and after every refresh.

### IEEE MAC registries <a href="#ieee-mac-registries" id="ieee-mac-registries"></a>

The `oui` row downloads the five public IEEE registries behind MAC Lookup (`/api/macchecker`) into `common/oui-db/` — about 5.7 MB together, no key:

| Registry | File        | Block                                               |
| -------- | ----------- | --------------------------------------------------- |
| MA-L     | `oui.csv`   | 24-bit vendor prefix (the classic OUI)              |
| MA-M     | `mam.csv`   | 28-bit block                                        |
| MA-S     | `oui36.csv` | 36-bit block                                        |
| IAB      | `iab.csv`   | 36-bit block (retired; existing assignments remain) |
| CID      | `cid.csv`   | 24-bit Company ID (locally administered space)      |

All five come from `standards-oui.ieee.org` and publish together as one set; the version is their `Last-Modified` headers joined, so any one changing is a new version. Each file must carry the registry CSV header and stay above a per-registry row floor, or the download is refused as truncated.

`server/datasets/oui-db.js` loads the five into one in-memory map at startup and after every refresh, and answers a query with the **longest** assignment covering it: MA-M, MA-S and IAB blocks sit inside MA-L prefixes registered to "IEEE Registration Authority", so the sub-block wins. The registries have no country column; the country is read off the end of the registered address.

### Updating <a href="#updating" id="updating"></a>

A row holds only its dataset's own logic — where the newest remote version is, how to fetch and distill it, a validator that refuses a truncated or corrupt download, and how to reload the in-memory copy. The engine owns the rest:

| Behavior                | Value                                                                                                                                                                                                                                                                   |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Boot download           | When the reader has nothing usable (files missing, or a file it refuses) or a previous publish was cut short. All rows in parallel, each capped at 5 minutes, behind an already-open listener; runs regardless of `DATASET_AUTO_UPDATE`                                 |
| Daily refresh           | At `DATASET_UPDATE_CRON` (default `30 4 * * *`, server-local time), rows one after another, each aborted after 30 minutes. Off with `DATASET_AUTO_UPDATE=false`; while that is unset, the older `MAXMIND_AUTO_UPDATE` / `CAIDA_AUTO_UPDATE` still decide for their rows |
| Missed runs             | Rows whose daily check fell while the server was down are caught up 60 seconds after boot                                                                                                                                                                               |
| Change detection        | Each row names the remote version (`Last-Modified`, or the dated filename); a refresh downloads only when it differs from the recorded one                                                                                                                              |
| Publishing              | Staged in the system temp directory and validated, then renamed into place together; any failed step rolls the set back                                                                                                                                                 |
| Concurrency             | A lock per dataset directory with a heartbeat, so a crashed holder's lock goes stale after 10 minutes                                                                                                                                                                   |
| State                   | `.dataset-state.json` per directory; an older updater's state file is read once, so an upgrade does not re-download                                                                                                                                                     |
| Files changed by others | Every dataset's files are polled every 5 seconds; once they stop changing and pass the row's validator they are reloaded — another process's publish or a hand-placed file alike                                                                                        |

{% hint style="info" %}
**Data terms.** The CAIDA datasets are distributed under CAIDA's Acceptable Use Agreement. PeeringDB records are self-reported by network operators, so the ASN Profile shows what a network says about itself, not a measurement.
{% endhint %}

### ASN Profile sources

`/api/asn-profile` adds no dataset of its own. It composes the local data above with three upstream lookups, each under its own deadline in `server/asn-profile.js`:

| Source           | Where                                                                                                                       | Notes                                                                                                                                                                                                                                                                                                                                                                                |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Cloudflare Radar | `api.cloudflare.com`                                                                                                        | The `asn` and `bgp-prefixes` views; `disabled` without `CLOUDFLARE_API_KEY`. The prefix list's country shares are computed locally against the MaxMind City database, each prefix split across the MaxMind networks it spans, under a per-request lookup budget. If MaxMind cannot answer or the budget runs out, the shares are left empty and `prefixes` is listed in `incomplete` |
| RDAP             | IANA's bootstrap file at `data.iana.org/rdap/` (cached in memory for 24 hours), then the responsible registry's RDAP server | The same RDAP client the Whois tool uses (`server/rdap.js`)                                                                                                                                                                                                                                                                                                                          |
| CAIDA AS Rank    | `api.asrank.caida.org` (GraphQL, no key)                                                                                    | Academic service with no SLA; a failure only marks the `rank` section                                                                                                                                                                                                                                                                                                                |

The full response contract is in [API Endpoints](https://docs.ipcheck.ing/developer/reference/api-endpoints.md#api-asn-profile).

## What happens when something fails

| Failure                                             | Result                                                                                                                                                                                                |
| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| One echo endpoint is down                           | `runChain()` advances to the next provider in that card's chain; if every provider fails the card shows nothing and emits `ip-source:exhausted`                                                       |
| One geolocation source has used up its daily limit  | Its route answers `429` with `code: "source_daily_limit"`; the card falls back to the next enabled source                                                                                             |
| One geolocation provider errors                     | The client falls back to the next enabled source and shows a toast; later queries start from the working source                                                                                       |
| Every geolocation source fails for an IP            | The card's detail fields stay empty; the error is logged client-side                                                                                                                                  |
| An upstream hangs                                   | `fetchUpstream` aborts at 8 seconds and the handler returns `500 { error }`                                                                                                                           |
| An offline dataset is still downloading at boot     | Routes reading it answer `503` with `Retry-After: 30`, never edge-cached; the ASN Profile reports the affected sections as `error`                                                                    |
| MaxMind databases missing or invalid                | `/api/maxmind` and `/api/bulk-lookup` return 503, and the ASN Profile's country shares come back empty, so that profile is edge-cached for a day instead of a week; the rest of the API is unaffected |
| CAIDA snapshots missing                             | `/api/asn-connectivity` returns an empty graph and the ASN Profile's `connectivity` section reports `error`; org-name lookups fall back to RIPEstat's `as-overview`                                   |
| IEEE MAC registries missing                         | `/api/macchecker` returns 503; every other route is unaffected                                                                                                                                        |
| PeeringDB index missing                             | The ASN Profile's `peeringdb` section reports `disabled` without `CLOUDFLARE_API_KEY`, and `error` with it; every other section is unaffected                                                         |
| One ASN Profile source fails or misses its deadline | Only that section is `null` with status `error`; the answer is still `200` but is edge-cached for 1 day instead of 7 (not at all while offline datasets are still downloading at boot)                |
| An upstream returns an HTML outage page             | `makeGeoHandler` throws on the non-2xx status before parsing                                                                                                                                          |

## Related pages

* [Backend](https://docs.ipcheck.ing/developer/architecture/backend.md) — guards, caching tiers, and the boot sequence
* [Adding an IP Data Source](https://docs.ipcheck.ing/developer/development/adding-an-ip-data-source.md) — the adapter, the registry rows and the tests for a new source
* [Optional API Keys](https://docs.ipcheck.ing/developer/configuration/optional-api-keys.md) — which sources need credentials
* [MaxMind Setup](https://docs.ipcheck.ing/developer/getting-started/maxmind-setup.md) — obtaining and refreshing GeoLite2
* [API Endpoints](https://docs.ipcheck.ing/developer/reference/api-endpoints.md) — the full request/response contract


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.ipcheck.ing/developer/architecture/ip-data-sources.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
