Searching Relationship Paths Without a Graph DB, Using an RDB and an In-Memory DB
#event-correlation#graph-traversal#pitr#postgresql#duckdb#recursive-cte#query-processing#graph-database#neo4j
Contents
In a distributed system architecture, data is scattered across many services and stores.
Graph DBs such as Neo4j are often adopted as the engine that connects this scattered data, without a thorough technical review.
Stories about adopting Neo4j are common on Threads and LinkedIn, but posts that clearly explain why a graph DB was needed are rare.
I am not entirely against adopting Neo4j.
However, I think the benefits of defining and searching relationships can be obtained at a lower cost without a graph DB.
This post introduces an architecture that adds DuckDB, an in-memory DB, to an existing PostgreSQL environment to implement relationship definition and path search flexibly.
There are two key points.
The units whose relationships matter are not raw records but the events that group them, and the paths actually needed at the moment an alert fires are only the small subgraph connected to the alert event.
The example throughout is a security operations scenario that connects separately collected records, such as a web shell upload, shell execution, a credential file read, and access to an internal DB server, into a single attack path.
1. Relationships between events, not raw records
Devices such as firewalls, WAFs, EDRs, and proxies leave several raw logs for the same action.
When a web shell is uploaded, a WAF log and an EDR file log are written together, and when the shell runs, an EDR process log and a proxy log are written together.
Trying to connect these raw logs one by one has the drawback that the number of units to relate grows with the number of raw logs.
So raw data is first grouped into meaningful units called events, and relationships are defined only between events.
Security operations products also usually handle raw logs grouped into events or alerts.
Because several raw logs become one event, the number of units to relate becomes much smaller than the number of raw logs.
The structure described below assumes this.
In the following figures, nodes labeled with host names such as web server or app server represent events that occurred on that host.
2. The TCO of always-on graph loading
TCO (Total Cost of Ownership) covers not only the cost of adoption but every cost of keeping a system running, such as writes, storage, synchronization, backups, operations, and licensing.
If every event is loaded into a graph DB as it occurs, the following costs grow with the number of events.
| Item | With always-on graph loading |
|---|---|
| Writes | Create nodes and relationships for every event and update indexes |
| Storage | Keep a graph copy separate from the source store |
| Consistency | Keep the source store and the graph DB in sync at all times |
| Backup | Back up both stores separately and align their recovery points |
| Operations | Size the cluster and tune memory |
Neo4j Community Edition is licensed under GPLv3, and features such as clustering require a commercial Enterprise Edition license.
The problem is that these costs apply equally to relationships that are never used by a path query.
In an environment where paths are queried from alerts, a path query actually uses only the small subgraph connected to the alert event, and the remaining relationships are stored and backed up without ever being read again.
3. The limits of replacing graph traversal with RDB recursive queries
Even so, computing paths directly in PostgreSQL without a graph DB can cause other problems.
PostgreSQL supports recursive queries with WITH RECURSIVE, but security data has a high fan-out.
Once a path passes through a node that talks to almost every host, such as a DNS server, a proxy, or a monitoring server, the next-hop candidates can grow into the tens of thousands.
Searching many hops across the entire source table can cause memory exhaustion, temporary disk use, and timeouts.
Also, when such queries run on the production DB, event ingestion slows down with them.
Graph traversal could also be implemented directly, but variable-depth search, cycle removal, time-order checks, and combinatorial explosion control would all have to be implemented and verified by hand, which makes maintenance expensive.
4. Separating relationship definition from path search
The core of this structure is separating the time when relationships are defined from the time when paths are searched.
- Definition stage: each time an event is created, 1-hop relationships between events are defined using anchor fields such as the same host, user, session, or the source and destination of a network connection, and stored in the DB
- Search stage: only when an alert or analyst request arrives, the defined 1-hop relationships are pruned and multi-hop paths are computed in a DuckDB in-memory session
A 1-hop relationship can be decided from a single event, so its cost is small and predictable.
Multi-hop paths, on the other hand, grow quickly in number with every hop, so only the range needed is computed at the moment it is needed.
In other words, storage and relationship definition are done in advance, and only multi-hop path computation follows a JIT (Just-In-Time) pattern.
| Principle | Reason |
|---|---|
| PostgreSQL is the only source of truth | Backup and recovery cover a single store |
| DuckDB is a library, not a server | No separate cluster, port, or account to operate |
| In-memory sessions are discarded after computation | No intermediate results are written to the source DB, and no state is left to sync |
| Only result paths are stored in the source | Only a few dozen path rows remain, so storage cost is small |
DuckDB is open source under the MIT license and runs as a library inside the application process without a separate server. There is also no need to prepare partitioning or a separate graph store from the start. If time window queries slow down as the retention period grows, time-based partitioning can be added then.
5. Why path computation is moved out of PostgreSQL
If PostgreSQL runs WAL-based PITR (Point-In-Time Recovery), computing paths inside PostgreSQL brings many additional concerns.
Path computation consists of several steps: pruning candidate edges, building intermediate results for each hop, and selecting the final paths.
If these intermediate results are written to regular tables, every write goes to the WAL, and the WAL archive and standby replication grow with them.
There are ways to avoid the WAL, but each has its own constraints.
| Method | Constraint |
|---|---|
| UNLOGGED table | Skips the WAL, but its contents are truncated after a crash and it is not replicated to standbys |
| Temporary table | Disappears at the end of the session, but each create and drop updates the system catalog, and autovacuum does not clean it |
| Compute on a standby | Hot standby sessions are read-only and cannot even write temporary tables |
| Compute in a single recursive query | Produces no WAL, but a heavy query shares the primary’s CPU and memory with event ingestion |
So PostgreSQL handles only source storage and pruning, and path computation is handed to DuckDB, an in-memory DB embedded in the application.
Intermediate results in a DuckDB in-memory session are independent of the PostgreSQL WAL, so multi-hop path search can be added without changing the PITR and replication setup already in operation.
6. Pruning the path search range
The fan-out problem described earlier does not go away when the computation moves to DuckDB.
The cost of recursive computation is determined by the number of input edges and the fan-out.
Therefore, pruning the number of edges loaded into DuckDB is more effective than making DuckDB faster.
However, this step cannot pick out only the edges actually connected to the seed.
Checking connectivity is itself a search.
So pruning only reduces candidates with conditions that can be judged from a single edge, and finding the paths reachable from the seed is the job of the DuckDB recursive CTE.
| Filter | Target |
|---|---|
| Time window | Relationships outside the range before and after the alert’s reference time |
| Hub anchor exclusion | Relationships created through an anchor value shared by too many events, such as a DNS server IP |
| Reflection noise exclusion | Relationships generated in bulk in both directions, such as scans or DoS |
| Edge folding | Repeated relationships with the same source, destination, and relationship type |
Whether something is a hub is judged by its degree, and degree can be counted from 1-hop relationships alone.
In relationships between events, an anchor value shared by too many events, such as a DNS server IP, acts as a hub, so it can be found simply by counting events per anchor value.
This count can be maintained in advance during the definition stage by updating a counter per anchor value as events arrive.
A predefined list and a cap on the number of events within the time window are used together to decide what counts as a hub.
However, excluding a hub anchor can also remove real paths that went through that value, so the list of excluded anchors must be kept with the result.
Pruning reduces computation cost but has the drawback that some paths may be missed. The conditions above are therefore tuned for each environment, and if a missed path is suspected, the search is run again with a wider time window or with the excluded anchors included.
7. Multi-hop path search with a recursive CTE
A DuckDB recursive CTE starts from the relationships leaving the seed event and adds, one hop at a time, the relationships leaving the arrival nodes of the previous step.
Connecting nodes alone would also produce paths that could never have happened, so the following conditions are applied together.
| Condition | Prevents |
|---|---|
| Add only relationships still alive after arrival | Including communication that ended before the attacker reached the node |
| Update the path’s arrival time cumulatively | Path timestamps running backward |
| Limit the maximum hop count | Unbounded expansion |
| Exclude nodes already on the path | Cycles such as A to B and back to A |
The comparison must be against the arrival time accumulated along the path, not the start time of the previous relationship.
Comparing against the start time of the previous relationship would let relationships from before the node was actually reached pass the condition.
Also, the DuckDB documentation notes that when a recursive CTE traverses a graph with cycles, cycle checks must be done explicitly to avoid infinite loops.
Rather than expecting a cap on the number of result rows to stop the expansion, the expansion itself must be prevented with a hop limit, cycle removal, pruning, and a per-node fan-out cap.
DuckDB recursive CTEs support USING KEY. For searches that only need to keep one value per key, such as the shortest distance per node, intermediate results are updated instead of accumulated, which reduces memory use.
Path search is handled by a fixed number of workers, and each session caps CPU and memory with DuckDB's threads and memory_limit settings. When alerts arrive all at once, they wait their turn in a queue, so the system runs as a backpressure structure in which processing is delayed instead of memory growing.
8. When a graph DB is the better fit
There are cases where a graph DB is the better fit.
- Graph algorithms such as unbounded traversal, shortest paths, or centrality are used routinely
- The same graph is explored repeatedly across many incidents and analysts
- The relationships are slow-changing ones such as assets, accounts, and permissions rather than events
On the other hand, for data such as event paths that is needed only temporarily when an alert fires and is mostly never read again, the cost of connecting everything in advance is higher.
References
- DuckDB WITH Clause (Recursive CTEs, USING KEY): https://duckdb.org/docs/stable/sql/query_syntax/with
- DuckDB Configuration: https://duckdb.org/docs/stable/configuration/overview
- DuckDB Why DuckDB: https://duckdb.org/why_duckdb
- PostgreSQL WITH Queries: https://www.postgresql.org/docs/current/queries-with.html
- PostgreSQL Continuous Archiving and Point-in-Time Recovery: https://www.postgresql.org/docs/current/continuous-archiving.html
- PostgreSQL CREATE TABLE (UNLOGGED, TEMPORARY): https://www.postgresql.org/docs/current/sql-createtable.html
- PostgreSQL Hot Standby: https://www.postgresql.org/docs/current/hot-standby.html
- Neo4j Licensing: https://neo4j.com/licensing/