You have a year of rotated access.log.*.gz files on a server, a question that grep cannot answer, and no appetite for standing up a log cluster to answer it. DuckDB reads those gzipped files directly, parses the combined log format with a regular expression, and writes the result as Hive-partitioned Parquet — after which the same questions run in seconds instead of minutes, against a dataset roughly a tenth the size. It is a single binary with no daemon, no port, and no background process, which is exactly why it fits on a machine that already has a job to do. The catch is that DuckDB will happily use every core and all your RAM if you let it, so the settings that cap it matter as much as the SQL.
What you’ll accomplish
- Read gzipped and plain log files straight off disk with
read_csv, and newline-delimited JSON logs withread_json_auto, without decompressing anything first. - Parse the nginx combined log format into typed columns using
regexp_extractwith named capture groups. - Write the parsed result to Hive-partitioned Parquet with
COPY ... TO ... (FORMAT PARQUET, PARTITION_BY ...). - Query that Parquet set locally or in an S3-compatible bucket through the
httpfsextension. - Cap
memory_limit,threads, andtemp_directoryso a heavy scan cannot destabilise the host it runs on.
Prerequisites
- DuckDB 1.x CLI. The official install script is
curl https://install.duckdb.org | sh; if you would rather not pipe a script to a shell, download the release archive from the DuckDB documentation and unzip it — one static binary, no dependencies.brew install duckdband the community packages work too, but distribution packages lag and several options below need 1.0 or newer. Check withduckdb --version. - Read access to the log directory. On most systems
/var/log/nginxisroot:admand mode 640, so run as a member ofadmor copy the files somewhere you own. Nothing here writes to the logs. - Disk headroom on a filesystem you control, roughly 15 percent of the uncompressed log volume for the Parquet output, plus scratch space for spilling.
- Outbound HTTPS and S3 credentials only if you plan to work against object storage.
- An honest expectation: this is analytics over data that has stopped changing. It does not replace a live tail, and the conversion is a batch job you schedule after rotation.
How it works
Three separate mechanisms do the work, and understanding which one is failing saves most of the debugging time.
The first is the file reader. read_csv is a table function: it takes a path or a glob, detects gzip from the .gz extension, and streams the file in vectors of a few thousand rows rather than loading it. A log line is not really CSV, so the trick is to declare a single VARCHAR column and a delimiter that cannot appear in the data — nginx escapes every byte below 0x20 as \xNN in its log variables, so a literal tab never survives into the file and makes a safe delimiter. That gives you one row per log line, untouched.
The second is Parquet itself. A Parquet file stores each column contiguously in row groups, with min and max statistics per column chunk. Ask for two columns out of nine and DuckDB reads only those two chunks — projection pushdown. Name a column in WHERE whose row group statistics rule out a match and it skips that row group without decompressing it — predicate pushdown. Together they are why the same question costs a fraction of a text scan.
The third is Hive partitioning, which is nothing more than a directory naming convention: y=2026/m=7/d=15/part-0.parquet. With hive_partitioning = true, DuckDB reads y, m, and d as real columns from the path, and a predicate on them is evaluated against the directory names before a single file is opened. Partition pruning removes files; predicate pushdown removes row groups inside the surviving files; projection removes columns inside the surviving row groups. Stacked, they are the whole performance story.
Step-by-step
-
Cap the resources before you run anything. DuckDB defaults to roughly 80 percent of system RAM and every core. On a box that also serves traffic, that is not what you want. Put the limits in
~/.duckdbrcso they apply to every session.SET memory_limit = '4GB'; SET threads = 4; SET temp_directory = '/var/tmp/duckdb'; SET max_temp_directory_size = '40GB'; SET preserve_insertion_order = false;Expected: each statement returns silently. Confirm they took effect:
SELECT current_setting('memory_limit') AS mem, current_setting('threads') AS threads;Expected output:
┌─────────┬─────────┐ │ mem │ threads │ │ varchar │ varchar │ ├─────────┼─────────┤ │ 4.0 GiB │ 4 │ └─────────┴─────────┘preserve_insertion_order = falseis the one people miss. It lets DuckDB reorder rows freely during a largeCOPY, which cuts peak memory substantially and costs nothing when the output is grouped by partition anyway. -
Read raw lines out of the gzipped files. Declare one column so the sniffer stays out of the way, and disable quoting so the quotes inside the log line are treated as ordinary characters.
SELECT line FROM read_csv('/var/log/nginx/access.log*', columns = {'line': 'VARCHAR'}, delim = '\t', quote = '', escape = '', header = false, ignore_errors = true) LIMIT 2;Expected: two complete, unmangled log lines.
198.51.100.24 - - [15/Jul/2026:04:12:07 +0000] "GET /pricing HTTP/1.1" 200 8214 "-" "Mozilla/5.0" 203.0.113.9 - - [15/Jul/2026:04:12:07 +0000] "POST /api/v2/orders HTTP/2.0" 502 166 "-" "curl/8.5.0"If a line looks truncated at a quote or a comma,
quoteorescapewas not disabled. Addfilename = truefor afilenamecolumn identifying the source file — useful when several vhosts share a directory. -
Parse the combined format into named groups.
regexp_extractwith a list of names returns aSTRUCT, so one function call gives you every field. DuckDB does not process backslash escapes in ordinary single-quoted strings, which means the pattern reaches the regex engine exactly as written.SELECT regexp_extract(line, '^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) ([^"]*)" (\d{3}) (\d+|-) "([^"]*)" "([^"]*)"$', ['remote_addr','ident','user','time_local','method','path', 'protocol','status','bytes','referer','agent']) AS g FROM read_csv('/var/log/nginx/access.log.1.gz', columns = {'line': 'VARCHAR'}, delim = '\t', quote = '', escape = '', header = false) LIMIT 1;Expected: a struct with every field populated, not a struct of empty strings.
{'remote_addr': 198.51.100.24, 'ident': -, 'user': -, 'time_local': 15/Jul/2026:04:12:07 +0000, 'method': GET, 'path': /pricing, 'protocol': HTTP/1.1, 'status': 200, 'bytes': 8214, 'referer': -, 'agent': Mozilla/5.0}Empty strings everywhere mean the pattern did not match — see troubleshooting. DuckDB uses RE2: no lookahead, no backreferences, but everything above is plain regular-expression syntax.
-
Turn the timestamp into a real timestamp and derive partition columns.
strptimewith%zyields aTIMESTAMP WITH TIME ZONE. Usetry_strptimein bulk conversions so one malformed line does not abort a job that has been running for ten minutes.SELECT try_strptime('15/Jul/2026:04:12:07 +0000', '%d/%b/%Y:%H:%M:%S %z') AS ts;Expected:
2026-07-15 04:12:07+00. ANULLhere means the format string does not match the log — check for a missing offset or a non-English month abbreviation. -
Write the whole set out as partitioned Parquet. DuckDB lets a later expression in a
SELECTlist reference an earlier alias, so the partition columns can be derived fromtsin the same projection.COPY ( WITH parsed AS ( SELECT regexp_extract(line, '^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) ([^"]*)" (\d{3}) (\d+|-) "([^"]*)" "([^"]*)"$', ['remote_addr','ident','user','time_local','method','path', 'protocol','status','bytes','referer','agent']) AS g FROM read_csv('/var/log/nginx/access.log*', columns = {'line': 'VARCHAR'}, delim = '\t', quote = '', escape = '', header = false, ignore_errors = true) ) SELECT try_strptime(g.time_local, '%d/%b/%Y:%H:%M:%S %z') AS ts, g.remote_addr AS remote_addr, g.method AS method, g.path AS path, TRY_CAST(g.status AS SMALLINT) AS status, TRY_CAST(g.bytes AS BIGINT) AS bytes, g.referer AS referer, g.agent AS agent, year(ts) AS y, month(ts) AS m, day(ts) AS d FROM parsed WHERE g.status <> '' ) TO '/srv/logs_parquet' (FORMAT PARQUET, PARTITION_BY (y, m, d), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE true);Expected: a progress bar, then the prompt returns with no error. Check what landed:
find /srv/logs_parquet -name '*.parquet' | wc -l du -sh /var/log/nginx /srv/logs_parquetExpected: one file per day-partition, and an output directory roughly a tenth of the uncompressed input. A representative run over a year of a moderately busy vhost produced 365 files, 3.1 GB of Parquet from 38 GB of raw text.
-
Handle JSON access logs the same way, with less work. If your nginx or application log is newline-delimited JSON, skip the regular expression entirely.
SELECT ts, status, path FROM read_json_auto('/var/log/app/access-*.json.gz', format = 'newline_delimited') LIMIT 3;Expected: three rows with columns already typed from the JSON values. If the sniffer picks the wrong type — a numeric-looking request ID inferred as
BIGINT— pin it withcolumns = ...and setsample_size = -1so the whole file is sampled instead of the first 20,480 rows. Structuring the log this way from the start is worth the effort; our guide to nginx log formats and rotation covers defining a JSONlog_format. -
Query the Parquet set. This is the payoff: the questions that used to be a pipeline of
zcat,awk,sort, anduniqbecome one statement.SELECT status, count(*) AS requests, sum(bytes) AS bytes_sent FROM read_parquet('/srv/logs_parquet/**/*.parquet', hive_partitioning = true) WHERE y = 2026 AND m = 7 GROUP BY status ORDER BY requests DESC;Expected output:
┌────────┬──────────┬──────────────┐ │ status │ requests │ bytes_sent │ │ int16 │ int64 │ int128 │ ├────────┼──────────┼──────────────┤ │ 200 │ 41829174 │ 812093774112 │ │ 301 │ 2210834 │ 412093774 │ │ 404 │ 1094522 │ 10940221100 │ │ 500 │ 18442 │ 204118820 │ │ 502 │ 2917 │ 31082910 │ └────────┴──────────┴──────────────┘ -
Put the Parquet in object storage and query it in place. The
httpfsextension addss3://,http://, andhttps://support. Install it once per DuckDB installation; it persists.INSTALL httpfs; LOAD httpfs; CREATE PERSISTENT SECRET logs_s3 ( TYPE S3, KEY_ID 'AKIAEXAMPLEKEYID', SECRET 'wJalrXUtnFEMIEXAMPLEKEY', REGION 'ca-central-1' );Expected:
INSTALLandLOADreturn silently, and the secret returns aSuccessboolean oftrue. For MinIO, Ceph RGW, or another S3-compatible endpoint, add the endpoint and force path-style addressing:CREATE PERSISTENT SECRET logs_minio ( TYPE S3, KEY_ID 'logreader', SECRET 'REPLACE_ME', ENDPOINT 'minio.internal.example.com:9000', URL_STYLE 'path', USE_SSL true );The same
COPYfrom step 5 writes straight to a bucket by changing the destination to's3://acme-logs/nginx', and queries read it back with the same path:SELECT path, count(*) AS hits FROM read_parquet('s3://acme-logs/nginx/**/*.parquet', hive_partitioning = true) WHERE y = 2026 AND m = 7 AND status = 404 GROUP BY path ORDER BY hits DESC LIMIT 5;Expected: five rows. Over object storage, DuckDB issues ranged GETs for the footer and only the column chunks it needs, so a query touching two columns of one partition transfers megabytes rather than gigabytes.
Validate it works
Prove no rows were lost in the conversion. Count both sides in a single statement:
SELECT
(SELECT count(*) FROM read_csv('/var/log/nginx/access.log*',
columns = {'line': 'VARCHAR'}, delim = '\t', quote = '',
escape = '', header = false, ignore_errors = true)) AS raw_lines,
(SELECT count(*) FROM read_parquet('/srv/logs_parquet/**/*.parquet')) AS parquet_rows;
Expected: the two numbers match, or differ by exactly the count of lines your WHERE g.status <> '' clause rejected. A gap you cannot account for means the pattern silently dropped valid lines.
Confirm nothing became NULL in the timestamp conversion:
SELECT count(*) AS null_ts
FROM read_parquet('/srv/logs_parquet/**/*.parquet') WHERE ts IS NULL;
Expected: 0. Anything else is try_strptime swallowing a format mismatch, which is the failure mode that quietly ruins a time-series chart.
Prove that partition pruning actually happens rather than assuming it:
EXPLAIN SELECT count(*)
FROM read_parquet('/srv/logs_parquet/**/*.parquet', hive_partitioning = true)
WHERE y = 2026 AND m = 7;
Expected: the READ_PARQUET operator in the plan carries a File Filters: line naming your partition predicate, and a Scanning Files: line showing a subset of the total — something like 31/3650. If File Filters is absent, hive_partitioning is off or the predicate references a column that is stored inside the files rather than in the path, and every file will be opened.
Finally, look at what the Parquet actually costs per column:
SELECT path_in_schema, count(*) AS row_groups,
sum(total_compressed_size) AS compressed_bytes
FROM parquet_metadata('/srv/logs_parquet/y=2026/m=7/**/*.parquet')
GROUP BY 1 ORDER BY compressed_bytes DESC;
Expected: agent and path dominate, status is tiny. That ratio tells you which column to drop if the output is bigger than you want.
Troubleshooting
Out of Memory Error: could not allocate block of size .... Almost always a largeCOPYor a high-cardinality aggregation. In order: setpreserve_insertion_order = false, lowerthreads(each thread holds its own buffers, so four on 4 GB behave better than sixteen), pointtemp_directoryat a filesystem with room to spill, and if it still fails, loop over the files a month at a time instead of globbing a year.SET memory_limitis a cap DuckDB respects, not a target it reaches for — raising it is rarely the fix on a shared box.regexp_extractreturns a struct of empty strings. The line does not match the pattern. Print one offending line withSELECT line FROM ... WHERE NOT regexp_matches(line, '<your pattern>') LIMIT 5and compare it field by field. The usual culprits are alog_formatwith extra variables such as$request_timeor$upstream_addrappended, a load balancer prefix, or$http_x_forwarded_forinserted mid-line. Anchoring with^and$is what makes the mismatch visible instead of silently partial, so keep the anchors while you debug.- Every
tsisNULL. Either the format string is wrong, or the machine that wrote the log used a locale where%bis not an English month abbreviation. Test one literal withstrptime(nottry_strptime) to get the actual parser error instead of a silentNULL. Logs written with$time_iso8601need'%Y-%m-%dT%H:%M:%S%z'instead. HTTP Error: HTTP GET error on ... (HTTP 403)orNo files found that match the pattern. Check what credentials DuckDB is actually using withFROM duckdb_secrets();— a secret created withoutPERSISTENTdisappears when the session ends. Against non-AWS endpoints, a 403 usually meansURL_STYLE 'path'is missing and the client tried a virtual-host style request.No files foundon a path you know exists is normally a glob problem:**/*.parquettraverses directories,*/*.parquetmatches exactly one level.- The conversion produced thousands of tiny files. Partitioning by day suits a year of one vhost. Partitioning by hour, or by day crossed with service and status, produces files whose footers cost more than their data, and object storage makes that worse because each file is at least two round trips. Repartition coarsely, and if a single
COPYfails with too many open files, raise the limit withulimit -nor split the job by month.
When this is the wrong approach
DuckDB is an embedded, single-process engine, and that is a design decision with consequences. Only one process can hold a write lock on a database file, so this workflow is one analyst or one scheduled job at a time. A dashboard that ten people refresh, or an alerting rule evaluating every thirty seconds, needs a server that manages concurrency — ClickHouse is the natural step up when the data stays tabular and the questions stay analytical.
It is also the wrong tool for live search. There is no tail, no streaming ingestion, no inverted index. Finding a request ID in the last five minutes of a running service is what Loki or OpenSearch exist for, and full-text ranking over free-form messages is not what a columnar scan does well. Log search and log analytics are different problems: keep a search system for incident response, and use DuckDB over Parquet for the aggregate questions a search system answers slowly and expensively.
Finally, if the data never gets big, do not build this. A few gigabytes of logs answer to awk in the time it takes to write the SQL, and the conversion job is one more thing to schedule, monitor, and eventually explain to whoever inherits it. Keep the DuckDB documentation open for the table functions and settings, and the Apache Parquet documentation for what the format guarantees about statistics and encodings.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.