Skip to content

Historical database (HDB)

This page explains how to serve a loaded KDB-X database to other users as an HDB process, and what limits a single process.

Loading a database in a single session is for that session's own use — a q prompt, a script, or a Python process using KDB-X Python. There is no server, and most analysis never needs one.

The step to take this into production is to keep such a process running and let other people query it. A q process that has loaded a database and serves queries over IPC is conventionally called an HDB (historical database) when the data it serves is historical. It is the same \l and the same mapping; what changes is that the process outlives the question and answers on behalf of others. There is still no database server to install — an HDB is just q, started against a database directory.

Beyond the data, an HDB almost always loads a script of its own:

q hdb.q -db /tmp/testdb -p 5010 -s 4

where -db names the database root and hdb.q loads it and defines everything the process is expected to expose:

o:.Q.opt .z.x
.Q.lo[hsym `$first o`db;0b;0b]

/ business logic clients call
vwap:{[t;s] exec size wavg price from t where sym=s}
/ constants and reference data
tickSize:0.01

That script is code: it belongs in version control and goes through review and release like any other code. The database directory beside it is data, and is not versioned the same way. Keeping the two apart is what lets one database be served by several processes running different releases of the logic, and lets the logic be rolled forward without touching a byte of data.

One query at a time

By default a q process is single-threaded and handles incoming messages sequentially, so an HDB serves one query at a time. While it is executing, other clients' requests wait in its input queue: one expensive or badly bounded query delays everybody connected to that process.

Secondary threads (-s) do not change this. They parallelize work within one query — across partitions and columns — so that query finishes sooner. But the process still takes one request at a time.

Multithreaded input mode rarely solves this

q has a multithreaded input queue mode that gives each connection its own thread. An HDB can use it on uncompressed data, but one query that exceeds the memory limit aborts every query in the process, the number of concurrent queries cannot be capped, the query timeout is not available, and on compressed data concurrent queries run slower than they would one at a time. See multithreaded input mode for the details, and for why a pool of HDBs is usually the better choice.

Handling concurrent queries

Concurrency for an HDB is solved by running more than one HDB against the same database, with something in front to spread the work across them — socket sharding, a kdb+ gateway, or a dedicated protocol-aware load balancer. See handling concurrent queries.

Garbage collection

The database columns an HDB maps are not on the heap, but everything a query computes is: intermediate vectors, grouped results, the reply being serialized. When the query finishes, q frees that memory. By default it keeps the memory on its heap for reuse instead of returning it to the operating system (see garbage collection). After a few large queries an idle HDB can still hold many gigabytes. This matters most when several HDBs share a host, because memory one process keeps is memory the others cannot use.

.Q.gc[] gives that memory back. On an HDB that serves large queries, call it periodically, for example from a timer, rather than wait for q to collect on its own. Otherwise q collects only when an allocation needs the memory, and then the pause happens in the middle of whichever query made the allocation.

An HDB cannot answer queries while it collects

When .Q.gc[] runs from a timer, -T does not apply to it, and every request that arrives during it waits in the input queue. Collecting a heap that has been freed completely is quick. A large, fragmented heap is not: on a 32 GB heap where a few small objects survived in most of the allocator's 64 MB blocks, .Q.gc[] took about 2.5 seconds, and it returned only 64 MB because the survivors pinned the rest. Run \ts .Q.gc[] on your own HDB under realistic load to find the cost.

In a pool of HDBs, plan the collections so that the pool keeps serving:

  • Do not let all HDBs collect at once. If every process runs the same timer, they tend to pause together and the whole pool stops answering. Stagger the schedules, or collect only when the heap is well above what is in use. .Q.w[] reports both as heap and used.
  • Take the HDB out of rotation first. Ideally the HDB tells the gateway or query router that it is unavailable, or disconnects from it, then collects, then announces that it is ready again. Queries go to the other HDBs instead of queuing behind the collection. If the gateway already tracks which HDBs are busy, it can also schedule collections itself, one HDB at a time, the same way it sends any other job to an idle HDB. With socket sharding neither option is available. Connections stay with the process they were assigned to, so staggering is the only protection.

Immediate mode (-g 1) suits an HDB whose queries build large intermediate results, because it returns their memory as soon as each query frees it. Smaller objects still stay on the heap until .Q.gc[] runs, so it reduces the need for periodic collection but does not remove it.

Reloading the database

An HDB sees the database as it was when it loaded it. A new partition written at the end of the day, a corrected partition, or a schema change is invisible to it until it loads the database again. Usually the process that writes the data, such as the end-of-day job, triggers the reload when it finishes. The HDB reloads by running the same load as at startup. In the hdb.q above that is .Q.lo[hsym `$first o`db;0b;0b], so it is worth defining it once as a function that the trigger calls. A reload also discards anything the process built on top of the load, such as the result of .Q.bv, so put those calls in the same function.

Not every write needs a full reload. Rows appended to a partition the HDB already knows, such as today's, need at most two much smaller updates: reading the new symbols from the sym file, and refreshing the cached row count of that partition. Reloading a database shows which change needs which, and defines a function for each, reloaddb, reloadsym, and reloadcache, for the writer to call.

Like garbage collection, a reload blocks the HDB. It runs in the main thread, after the query in progress, and no queries are served until it finishes. For a full reload, the time is mostly spent reading the sym file and listing the partitions. This is typically quick but it can also last for seconds. The smaller updates block too, but for much less time: refreshing a partition count, or reading only the new symbols, takes about a millisecond. Reading the whole sym file again takes time in proportion to its size, about half a second for 10 million symbols, so on a large sym file treat it like a full reload. Queries that arrive in the meantime wait, either in the HDB's input queue or in the gateway or query router. The router is the better place for them to wait, because it can still send them somewhere else and an HDB's input queue cannot.

A single HDB has nothing to coordinate. In a pool of HDBs, send the reload trigger to the router rather than to each HDB, so that the router decides when each HDB reloads.

The quick updates need no scheduling. The router can pass them to every HDB straight away, without stopping dispatch or taking any HDB out of rotation, and the HDBs pick up the change within moments of each other. For new symbols, the router confirms to the writer only once every HDB has read them, and the writer appends its rows after that, so that no HDB shows the new symbols as null.

A full reload is slower, and there are two ways to schedule it:

  1. Reload all HDBs at once. The router stops dispatching new queries, waits for the running ones to finish, tells every HDB to reload, and resumes when all of them have confirmed. Queries queue in the router for the longest running query plus the reload time. In return, the pool always answers from one version of the data.
  2. Reload the HDBs one at a time. Take each HDB out of rotation as for garbage collection, reload it, and put it back. The pool keeps serving with one HDB fewer. The caveat is that a reload is not atomic across a pool. Until the last HDB has reloaded, some HDBs answer from the new data and some from the old, so the same query sent twice at the same moment can return different results. A client that splits one piece of work over several queries can get answers from both versions. If the router knows which HDBs have reloaded, it can send queries that need the new data, such as those on the new partition, only to them.

Choose the first option when consistent answers matter more than a short pause for every client, and the second when the pool must keep answering. Either way, a pool reload is also a good moment to run .Q.gc[], because no queries are being sent to the HDB anyway. With the second option, the old files remain in use until the last HDB has reloaded, so delete them only after that, as changing a database that is being queried describes.

Query timeout

A single query can keep a q process busy for a very long time — an unbounded select over every partition, an accidental cross join, a scan with no constraint on the partitioning column — and because an HDB serves one query at a time, that one query blocks every other user connected to it.

The -T command-line option puts a ceiling on it: -T n aborts any client call still running after n seconds with 'stop and leaves the process free to take the next request, so a runaway query costs one client an error instead of stalling everybody. The default is 0, meaning no limit, and \T changes it in a running process.

Note that it applies only to calls arriving over IPC — work typed at the console or run from a startup script is never interrupted, so testing -T in a local session appears to do nothing.

In practice it is rarely possible to choose a limit that separates good queries from bad ones. A valid analysis over months of data can legitimately run for minutes, and from its running time alone it looks no different from a query that is long only because it forgot to constrain the date. A limit low enough to stop the accidental queries also stops the legitimate long ones, and a limit high enough to let those through no longer protects the other users much. So treat -T as a safety net that is set well above the longest expected query, not as a way to keep the HDB responsive. Keeping it responsive is better done by checking queries before they run, and by sending long-running work to HDBs of its own. A gateway can do both.

Next steps