When datastore_upsert beats reloading a file in CKAN DataStore
If your sensor or transport feed changes every few minutes, reloading the whole file on each cycle means consumers wait for a full rebuild before they see new rows. The datastore_upsert action writes changed rows into an existing DataStore table by primary key instead of replacing the file, so the table is updated in place and consumers keep querying the same resource. According to the CKAN DataStore documentation, the DataStore keeps resource data in its own PostgreSQL database and exposes it through the Data API for filtering, search, pagination and SQL queries. The main decision is whether your source emits individual records that have stable keys, or whether each publication is a complete snapshot of the dataset.
Upserts suit feeds where each record has a stable identifier, such as a sensor or vehicle ID combined with a timestamp, and where most rows stay the same between runs. Confirm that your key is unique and never reassigned before you commit to it, because a reused key can overwrite the wrong record. Periodic full snapshots are simpler when the source publishes complete files, when the dataset is small enough that a reload finishes well inside your publishing interval, or when consumers need an exact copy of each published state. Deletions need attention in either design. Confirm whether the action removes rows that are missing from a new batch. If it does not, plan a separate cleanup step so that records the source has dropped do not remain in the table indefinitely.
Before you build, write down three things: the primary key columns, the expected share of changed rows in each cycle, and the longest acceptable delay between a source change and a consumer seeing it. Then check the parameters for your CKAN release. The method names for insert, update and upsert, the dry-run option and the request format for records depend on the version you run, so confirm them against the documentation for that release before you write any code. Test with a dry run against a copy of the table, and confirm how the action reports a batch that contains one invalid row, so your loader can log and retry it without losing the rest of the batch.
Insert, update and upsert methods compared
This table compares the insert, update and upsert methods of datastore_upsert, with a full reload for reference. Each row shows what a method does to existing rows and how it handles missing or repeated keys. The primary key is what makes those outcomes predictable, and upsert suits most live feeds, while a full reload stays simpler when the feed rewrites most of the table.
| Method | What it does to existing rows | Missing or repeated keys | When it fits a feed |
|---|---|---|---|
| Insert | Adds new rows only. Existing rows with the same key are not changed. | Confirm whether a repeated key is rejected or skipped in your version. | Append-only feeds where each record is new and is never revised. |
| Update | Changes existing rows matched by key. It does not add new rows. | Confirm whether a key with no matching row fails or is skipped. | Feeds that correct known records, such as revised readings, without adding new ones. |
| Upsert | Updates rows whose key already exists and inserts rows whose key is new. | Repeated keys within one batch need a rule. Confirm how the action handles duplicates. | Live sensor or transport feeds where each run carries both new and revised records. |
| Full reload | Rebuilds the table from a whole file, so row-level matching does not apply. | No key matching is needed, since the whole table is rewritten. | Small tables, schema changes, or feeds that rewrite most rows on every run. |
| Primary key | Field that identifies a row across runs. Update and upsert depend on it. | Missing or non-unique key values make matching unpredictable. Confirm key rules for your version. | Every feed updated in place needs an agreed key before the first load. |
Every upsert enters through one authenticated write path
The flow starts with a feed publisher or ETL job that sends changed rows to the CKAN API, authenticated with an API token from a user who holds write rights on the resource. The datastore_upsert action matches each row to an existing record by primary key, updating matches and inserting the rest. The write user boundary is where changes enter the DataStore PostgreSQL table. A dry run stops the flow after validation and returns a report, so no rows change. Use it to test each feed before enabling writes. Consumers read through the Data API under the read-only user, which cannot alter the table.
Writes enter through one authenticated API path; reads leave through a separate read-only path.
Setting up datastore_upsert on a CKAN DataStore resource
This sequence moves a frequently updated feed from a checked key column to a DataStore table that accepts repeat upserts without drifting from the source. Each step ends with a check, so the team knows the table matches the feed before any scheduled job runs. The result is a resource that the Data API serves accurately after every update.
Confirm the API token and write permissions
Before any upsert, the team running the job needs a CKAN API token tied to a user who can edit the target dataset and resource. Create the token from the user profile, store it in the job's secret store, and keep it out of scripts and version control. Confirm the account is an editor of the owning organization by running a read call such as datastore_search against the resource, then a write call against a scratch resource. The step is done when both calls succeed for that token. Read the CKAN DataStore documentation for the permission model before you go further.
Choose and test the key column
Pick the column that identifies one record over time, such as a vehicle ID, a station code, or a combination of two fields if the feed has no single identifier. Load a copy of the feed into a spreadsheet or a short script, then compare the number of rows with the number of distinct key values. The step is done when those two counts match and no key value is empty. If they differ, check whether the feed repeats records across snapshots or reuses identifiers before you go further.
Create the DataStore resource with the key
Create the table with datastore_create, passing the resource ID, explicit column definitions, and the key column as the primary key. Set column types deliberately so that later upserts match the values you tested. Then call datastore_search on the new resource. The step is done when the response lists the expected fields and the total is zero, which confirms the table exists and is empty before the first load.
Load the initial snapshot
Load the full feed once so the table starts from a known state. Use the loader your portal runs, such as XLoader for uploaded or linked files, or a single datastore_upsert call with the insert method for a snapshot you have prepared. The data owner should confirm the source row count before loading. The step is done when the total reported by datastore_search equals the source row count and the key check from the earlier step still passes.
Run a first test upsert on a small batch
Send a small test batch through datastore_upsert using the upsert method. Include one record whose key already exists with a changed value, one record with a new key, and no other rows. Record the total before and after the call. The total should rise by one, and the changed value should appear in the table. The step is done when the table shows exactly the two changes you sent and no other rows moved.
Repeat the upsert to confirm it changes nothing
Send the identical payload from the previous step a second time. Upserting the same rows again should leave the table unchanged, so the total and the sampled values must stay the same. Compare the counts and a sample of rows before and after the second call. If the total grows or a value changes, the key column is not identifying records reliably, and the job should not be scheduled yet. The step is done when two consecutive runs leave the table identical.
Verify rows through the Data API
Query the resource the way downstream users will, using datastore_search with a filter on the key column and a count across the full table. Compare returned values with the source for a sample of keys, including the two test records. Check that public read access works with the read-only path your portal uses, since the write user and the read-only user have different permissions. The step is done when sampled rows match the feed exactly and the total matches the source count.
Schedule the job and record expected counts
Before scheduling, write down the expected row count and the key check results so each scheduled run can be compared against them. Place the upsert call in your scheduler, reading the token from the secret store, and log the response counts for every run. Confirm the schedule with one manual run. The step is done when that run produces the same counts as your last test and the logged results match the expected values.
Choosing upsert, append or full reload by feed pattern
Frequent sensor readings usually arrive as a steady stream of new measurements from a fixed set of devices. Each reading needs a stable identifier, such as a device ID combined with a measurement time, so that a repeated reading matches its existing row and updates it, leaving one copy in the table. Upsert fits this pattern best, because gateways often retry after a network fault and the same batch can arrive twice.
- Key design: Combine the device identifier with the measurement timestamp, or use a reading ID the device issues. Confirm that no two devices can produce the same key.
- Clock handling: Devices with drifting clocks can produce timestamps that collide or sort out of order. Ask the device team how time is set and which time zone is stored.
- Batch dry runs: Run a sample batch through a dry run first to confirm which rows would be inserted and which would be updated before live traffic starts.
- Table growth: Historical readings grow without a fixed ceiling. Agree with the data owner how long readings stay in the DataStore and how older rows are handled.
- Risk if mismatched: Appending retried batches duplicates readings and skews averages. A full reload of a live stream replaces history the gateway no longer sends, so older readings disappear from the published table.
Before go-live, replay one batch twice and confirm that the row count does not change.
Transport feeds such as timetables and service updates add trips and stops, cancel them and retime them, often in a file that is republished in full or in part. Upsert fits when each trip and stop carries an identifier from the operator, so a retimed trip updates the row it already occupies. Cancelled trips need an explicit decision, because a plain upsert generally leaves a row in place when it no longer appears in the new file.
- Stable identifiers: Use the operator's trip and stop IDs as keys, and confirm that they stay the same across feed versions and service changes.
- Cancellation handling: Add a status column or a separate cleanup step for cancelled trips. Confirm with the operator whether cancelled identifiers are ever reused.
- Feed version tracking: Store the feed publication time or version in a column, so an older file that arrives late cannot overwrite newer retimings.
- Processing order: Load files in publication order. A retry of an old file after a newer one can restore outdated departure times, which riders will see as wrong.
- Risk if mismatched: Appending each publication duplicates every trip, which breaks counts and lookups. A full reload is simpler to reason about, but users may see partial data while the load runs, depending on how the reload is staged.
After each load, compare a sample of retimed and cancelled trips with the operator's live feed.
Snapshot publishers send the complete dataset on each run, so each file is the authoritative state at that moment. A full reload usually fits because it replaces the table with exactly what the publisher sent, including rows removed upstream. For loader behavior and how loaded tables are served, see the CKAN DataStore documentation.
- Staged replacement: Load the new snapshot into a separate resource or table, check it, and switch the published resource only after checks pass, so users never see a partial dataset.
- Comparison checks: Compare row counts and the set of keys with the previous snapshot before publishing. Flag sharp, unexpected drops for review.
- Keys still matter: Define a primary key even for reloads, so duplicates in the publisher's file are caught before they reach consumers.
- Reload cost: Each run rewrites the whole table, so run time grows with file size. Confirm the file size limit and job timeouts with the team that runs the portal's loader.
- Risk if mismatched: Upserting snapshots keeps rows the publisher has removed, so the table drifts from the source. Appending duplicates the full dataset on every run.
After each reload, confirm that removed records are absent and that the row count matches the publisher's manifest, if one is provided.
Failure modes that corrupt a live DataStore table
Five failure modes corrupt a live table without raising an obvious error. Each one looks like a successful load, so the early signals sit in row counts, error responses and value ranges.
Duplicate or unstable keys
A primary key that is not unique in the feed makes each upsert overwrite the previous row, so a sensor or vehicle can lose readings without any error. Keys built from values that change between exports, such as a timestamp re-stamped on each run or a position-based row number, make the same entity appear as new rows on every load. Watch for table row counts that grow faster than the number of entities in the source. Choose a key that identifies the entity and the event, such as device ID plus measurement time, and test its uniqueness on a full export before the first load.
Removed rows that stay
Upsert only inserts and updates the rows it receives. When a station, route or record drops out of the feed, its last row stays in the table and keeps appearing in searches, downloads and dashboards as if it were current. Teams often notice only when a consumer reports stale values. Track how many rows have not been seen in the feed for longer than the update interval. Decide before go-live whether removed items are deleted, flagged with a status column, or cleared by a separate scheduled job, and confirm how your CKAN version handles deletion before relying on it.
DataStore docsType drift from the feed
A column keeps the type it received on its first load. If the feed later sends a number as text, an empty string for a missing value, or a decimal with a comma, rows may be rejected or stored in a form that breaks numeric filters and sorting. Loaders that infer types from a small sample can guess wrong, and a column loaded as text stays text until it is reloaded or its type is changed. Check for rejected records in each upsert response and for numeric queries that suddenly return no rows. Validate each batch against the column types you expect before it is sent.
Partial batch failures
An upsert run sends many records across several requests. If a request fails partway through, some rows carry the new values and others still carry the old ones, so the table matches no single version of the feed. The table looks healthy at a glance because most rows are current. Treat any run that ends with an error or with fewer rows than the source export as incomplete. Make each run safe to repeat: use stable keys, keep the source snapshot for the run, and rerun the full batch after any failure.
Source schema changes
A renamed, removed or reordered field in the source can map values into the wrong column without an error, because the upsert matches on the names it is given. A new field that the table does not yet have may be dropped or may fail the call, and you should confirm which behavior your CKAN version shows. Watch for a change in the header or field list of the feed, and for a sudden shift in the value range of one column. Run a schema check before every load, record the expected field list with the resource, and agree on a change process with the feed owner before the next scheduled load.
Why a full reload is still simpler for many datasets
A full reload through the standard loading path is often the simpler choice when a file is small, when the publisher releases a complete snapshot on a fixed schedule, or when the feed has no column that uniquely identifies a row. In those cases, key design, duplicate checks and change tracking add effort without changing what consumers see. The trade-off is that every reload rewrites the whole table, so load time and database churn grow with file size and run frequency. The replacement also opens a timing gap. Confirm in your own environment how DataStore queries behave while a reload is running, because that depends on how your loader replaces the table, and decide whether your consumers can tolerate that window.
What you gain is no key design and no stale rows. A full reload needs no primary key decisions, no duplicate handling and no logic to find rows the publisher removed, because the new file is the entire table. Deleted records simply disappear on the next load. The pipeline is also easy to audit: one source file produces one table, and the load can be repeated from the same file if something goes wrong. Before you commit, check three things: whether the source is a complete snapshot, how many rows and how large the file is, and how often it changes. An illustrative daily file with no stable identifier usually fits this path, while a sensor feed that updates continuously usually does not.
Once you have chosen a reload, the remaining decisions concern the loader and how consumers reach the data. The sibling pages on loader selection and migration cover the loader options, so settle that first, then review the row-limit and download guidance before you publish a large table. Keep a short reload runbook that names the source file, the resource it feeds, the loader job and the check that confirms row counts after the load. Revisit the decision if the file grows, if the publisher begins sending only changed rows, or if consumers report problems during the replacement window. At that point, the upsert method described in this topic is the better fit.
Security and operational controls for a write path into live data
The upsert path lets a job change live rows that anonymous visitors read through the Data API, so it needs its own controls. The five cards cover identity, database roles, audit trail, secrets and feed validation, and each one is a decision you can check in your own environment before the first production run.
Dedicated publisher token
Give the publisher job its own CKAN user and API token, created for that job alone and limited to the organization and datasets it updates. Never reuse a maintainer's personal token, because a leaked personal key exposes every dataset that person can edit. Confirm which CKAN role the publisher user holds, whether your CKAN version can restrict a token to a single resource, and how quickly you can revoke the token if the job host is compromised.
Separate publisher from public reads
The DataStore keeps a write user and a read-only user in its own PostgreSQL database, and public queries should only ever use the read-only user. The publisher should reach the DataStore only through the CKAN API with its token, and should never hold database credentials. Test the split before go-live by confirming that the read-only user cannot insert or update rows. Confirm that your connection settings and any replicas follow the same split.
DataStore docsBatch-level write logging
Record each upsert as a batch with the publisher identity, resource ID, timestamp, insert and update counts, and a hash of the source file. Keep one log entry per batch so you can answer who changed a row and which feed produced it when a value looks wrong. Confirm whether your CKAN activity stream captures DataStore writes in your version, whether the job host keeps its own log, and how long each log is retained.
Secrets for the publisher job
Keep the API token and any connection settings out of source control, container images and job definitions. Load them at run time from a secrets manager or encrypted store your team already operates, and restrict which service accounts can read them. Scrub tokens from job output and error messages. Plan token rotation before the first run so that replacing a credential does not stop the feed. Confirm your rotation schedule, who holds emergency access, and whether the job runner logs request headers.
Protecting live data from bad feeds
A malformed or truncated feed can upsert valid-looking rows that overwrite good ones, so the job should decide whether a batch is safe before it writes. Validate every batch before the write: check that primary key values are present and unique, that required columns exist, and that the row count is plausible for that feed. Run a dry run for each new feed format, and keep the last accepted snapshot so you can restore it. Confirm how your team restores a bad batch and who approves the restore.
Questions teams ask before building live DataStore updates
What drives the cost and effort of an upsert pipeline?
Effort rises with how unpredictable the feed is and how many systems the pipeline touches. The work falls into four parts:
- Feed analysis: reviewing sample files to see how rows change, how timestamps behave and whether deletions are sent.
- Key design: choosing the primary key and upsert method so repeated runs do not create duplicate or stale rows.
- Publisher integration: building the job that pushes rows, including its scheduling, retries and credentials.
- Testing and monitoring: dry runs, row count checks and alerts when a run fails.
DeployOpen is paid for the analysis, design, build and test work in the written scope. Your organization pays staff time to provide feed access, review decisions and own the publishing system.
Which parts of an upsert pipeline are one-time and which recur?
Feed analysis, key design, the initial build and the first round of testing are one-time costs. A new feed or a change in the source system repeats part of the analysis. Recurring costs are the running job, monitoring, handling schema changes from the publisher and CKAN upgrades that touch the DataStore or the job. If you want DeployOpen to keep watching the pipeline, ongoing support, upgrades and continuous testing are available as retainers, and the retainer scope should be written down before work starts. Ask for the quote to show one-time and recurring amounts separately so you can compare them with your internal run costs.
How long does it take to build a live DataStore update pipeline?
The duration depends on the feed and the environment, so no fixed figure applies across projects. The main factors are how many feeds are in scope, how consistent their keys and timestamps are, whether the publisher can be changed, and how quickly a test CKAN instance and credentials are available. Most engagements are fixed-scope, so the timeline, deliverables and acceptance checks are agreed in writing before work starts. Ask for a written scope that lists each feed, the test environment, the milestones and the dependencies on your team, and treat any duration without that list as an estimate to confirm.
What do we need to provide for an upsert project?
Four inputs decide whether the work starts on schedule:
- Feed samples that cover normal runs, late or corrected records, and deletions if the publisher sends them.
- A test CKAN instance with a DataStore set up like production, so dry runs are safe.
- An API token held by a service account in your organization, with write rights limited to the target datasets.
- A named owner who decides on keys, schema changes and acceptance.
Share these before scoping so the quote reflects your environment. In return, the agreed scope defines what you receive, such as the pipeline code, its documentation and handover to your team.
Can our internal team build live DataStore upserts without a partner?
Yes, if the team already runs CKAN in production and has engineers comfortable with Python, the CKAN API and PostgreSQL. Check four skills before deciding: writing a job that calls the DataStore API with retries, designing keys from messy source data, testing changes against a non-production portal, and running monitoring that someone actively reads. The harder question is who owns the pipeline after go-live, especially if the engineer who built it also runs the portal. If any of those skills is missing, a partner can cover that part under a written scope while your team keeps ownership. Confirm the skills against your own environment and staffing before deciding.
When is a full reload simpler than live DataStore updates?
A full reload is simpler when the publisher replaces the whole file each time, when the table is small enough to reload quickly, or when no stable primary key exists. It also fits when consumers need a consistent snapshot that does not change while they read it. Deletions are a common reason to reload: if the source drops records without saying so, upserts will keep them. Reloading also avoids drift between the feed and the table. Read the CKAN DataStore documentation to confirm that the loader and table size suit a reload before you commit to live updates.
How do we test an upsert before it changes live data?
Run the job as a dry run against a test CKAN instance with a copy of the target table, then compare row counts, key uniqueness and a sample of changed records before enabling the schedule on production. Specific checks include confirming that the primary key is unique within each source batch, that updates touch only the expected columns, that the job rejects malformed rows and does not write them, and that a failed run leaves the table in a known state. Record the results as acceptance evidence for the scope. If the test data lacks late or deleted records, the test proves little, so request those samples before scoping.
How DeployOpen scopes and supports live DataStore feeds
DeployOpen plans and implements CKAN in infrastructure you control, including the DataStore tables that feed live data through the Data API. For upsert-based feeds, we start from the primary keys, update and insert rules, and the cases where a full reload is still the simpler choice. Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
How we scope
- The written scope names each DataStore resource, its primary key columns and its write method.
- Scope also covers the feed source, expected row volumes, update frequency and how bad or missing rows are handled.
- Engagements are fixed-scope, and ongoing feed support can be added as a retainer after go-live.
How we build
- Build the primary key and upsert path against sample extracts of your feed before any live writes.
- Test dry runs, duplicate keys, late-arriving updates and removed records against the DataStore in your environment.
- Confirm the write user and read-only user see the table as the feed owners expect.
How we hand over
- Hand over a runbook covering the upsert job, the expected key columns, and the steps for a full reload.
- Include a written record of the scripts, schedules and configuration that write to each DataStore table.
- Walk your team through monitoring, the retest steps and the criteria for switching a feed to a full reload.
How we support
- Retainers can cover upgrades, feed failures and source schema changes after go-live, as agreed in writing.
- Confirm with your team which errors the upsert job should alert on and who responds out of hours.
- Keep CKAN on a supported release line, since patch releases lose support once a newer patch is out.

