Searching Relationship Paths Without a Graph DB, Using an RDB and an In-Memory DB

architecture10 min한국어

#event-correlation#graph-traversal#pitr#postgresql#duckdb#recursive-cte#query-processing#graph-database#neo4j

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.

WAF log EDR file log Firewall log EDR process log Proxy log … Event grouping Many raw logs into one Event A Web shell upload Event B Shell execution Define relationships Same host, time order
Relationships are defined only between events that group raw records, not between the raw records themselves.

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.

ItemWith always-on graph loading
WritesCreate nodes and relationships for every event and update indexes
StorageKeep a graph copy separate from the source store
ConsistencyKeep the source store and the graph DB in sync at all times
BackupBack up both stores separately and align their recovery points
OperationsSize the cluster and tune memory

Neo4j Community Edition is licensed under GPLv3, and features such as clustering require a commercial Enterprise Edition license.

Always-on graph Compute on demand All events PostgreSQL Source Graph DB Graph of all events Sync, two backups Path query On the graph DB All events PostgreSQL Single source of truth DuckDB session Search range only pruning Result Session discarded after use
Always-on loading keeps every event in two stores, while on-demand computation works only on the range connected to the alert event, and only temporarily.

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.

Recursive query directly on production PostgreSQL Alert event Seed Web server hop 1 DNS server Hub node Talks to every host Host Host Host Host Host Host Host Candidates grow to tens of thousands Searching many hops across the full source table Out of memory Paths keep growing Temp disk use Intermediates spill to disk Timeout Query never finishes Ingestion slows Whole production DB slows
Once the search passes a hub node, next-hop candidates grow sharply, and the load spreads to the whole production DB.

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.

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.

Definition stage - every time an event is created Raw data Logs, telemetry Event grouping Many raw logs into one Define relationships 1-hop edges between events PostgreSQL Events and relationships Search stage - only when an alert fires Alert, request Seed, reference time pruning PostgreSQL function Drops unneeded edges Path search DuckDB in-memory session Recursive CTE, discarded Result Paths stored in PostgreSQL To analysts, triage model Read edges
Relationships are defined when events are created, and paths are searched separately when an alert fires.
PrincipleReason
PostgreSQL is the only source of truthBackup and recovery cover a single store
DuckDB is a library, not a serverNo separate cluster, port, or account to operate
In-memory sessions are discarded after computationNo intermediate results are written to the source DB, and no state is left to sync
Only result paths are stored in the sourceOnly 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.

MethodConstraint
UNLOGGED tableSkips the WAL, but its contents are truncated after a crash and it is not replicated to standbys
Temporary tableDisappears at the end of the session, but each create and drop updates the system catalog, and autovacuum does not clean it
Compute on a standbyHot standby sessions are read-only and cannot even write temporary tables
Compute in a single recursive queryProduces 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.

Computed inside PostgreSQL DuckDB embedded in the app Path computation Intermediate tables WAL writes Every intermediate write Standby replication Grows with it PITR archive Grows with it PostgreSQL Serves pruned edges DuckDB session Intermediates in memory Stores result paths only WAL, archive, and replication stay as they are
Keeping intermediate results in DuckDB memory leaves the WAL, the PITR archive, and the replication setup unchanged.

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.

All event relationships Every defined 1-hop relationship Seed Hub Edges pile up on hubs, and candidates grow with every hop pruning Per-edge rules drop candidates DuckDB input Candidates left after pruning Web server (seed) App server DB server External IP File server Recursive CTE finds seed paths
Pruning reduces candidates with conditions that can be judged from a single edge, and DuckDB finds the paths reachable from the seed.
FilterTarget
Time windowRelationships outside the range before and after the alert’s reference time
Hub anchor exclusionRelationships created through an anchor value shared by too many events, such as a DNS server IP
Reflection noise exclusionRelationships generated in bulk in both directions, such as scans or DoS
Edge foldingRepeated 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.

Anchor step Iteration 1 Iteration 2 Web server Seed App server At hop 1 DB server At hop 2 File server At hop 2 External IP At hop 3 hop 1 hop 2 hop 2 hop 3 Nothing to add Relationships from the seed Relationships from previous arrivals Stops at no new rows or max hops
The recursive CTE starts from relationships leaving the seed and, on each iteration, adds relationships leaving the previous step's arrival nodes, one hop at a time.

Connecting nodes alone would also produce paths that could never have happened, so the following conditions are applied together.

ConditionPrevents
Add only relationships still alive after arrivalIncluding communication that ended before the attacker reached the node
Update the path’s arrival time cumulativelyPath timestamps running backward
Limit the maximum hop countUnbounded expansion
Exclude nodes already on the pathCycles such as A to B and back to A
Web server Seed, 09:02 App server Arrived at 09:02 DB server Edge 09:06 - 09:20 Backup server Edge 08:40 - 08:50 09:02 Still alive after arrival Ended before arrival, excluded
The next edge is added only if it was still alive after the previous node was reached.

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