[EN] ChDB or DuckDB on AWS Lambda: A Technical Comparison — #3 Benchmark Cost Analysis of Data Replication in a Data Lake

[EN] ChDB or DuckDB on AWS Lambda: A Technical Comparison — #3 Benchmark Cost Analysis of Data Replication in a Data Lake

Building and running DuckDB and ChDB functions within AWS Lambda across several common use cases for data replication in a data lake—a classic data ingestion pattern—in order to conduct a technical comparison focused on both financial and technical costs.

AWS UG Arequipa Leader | AWS Community Builder - Data | AWS X4 | Data Engineer
I have already introduced lightweight data pipeline processing in this series through  Data Replication in a Data Lake and Its Performance Perspective . In that article, I showed that DuckDB is a good starting point for building these processes, while ChDB is another option worth exploring depending on the data format and performance requirements. These are important considerations for any data engineer implementing this type of solution.
To complete the initial overview of this technical comparison, we need to address a topic that is particularly important to the business and that you will almost always be asked about when proposing a solution: Costs.
And this is not just about financial costs, but also about the technical aspects surrounding the solutions discussed in the performance article — what is commonly known as technical debt.
This matters because the efficiency gained (or lost) by these processes may translate into additional costs for another process further downstream in the lightweight data pipeline.
So, the question we need to answer is:
🤔💭 Which is more cost-efficient, both financially and technically, when running on AWS Lambda: DuckDB or ChDB?
To understand where these costs come from, we need to look at the data architecture and answer another question: How do the generated files affect the performance and costs of other components within the data pipeline and the data lake?
👀 Remember that this analysis focuses on the data replication process within a data lake.



Understanding Costs from a Data Architecture Perspective

The core of the costs within a data lake lies in the physical structure of the table you will read from and write to. By physical table structure, I mean how the data is organized, the size of the files, and how many files are stored within the table.
From a high-level perspective, read operations in a data lake generally involve accessing the storage location and listing the files to determine which ones to select according to the query engine's requirements. Next, the engine retrieves the metadata to build an internal structure for interpreting the data. Finally, if required, the data can be loaded partially or entirely into RAM.
On the other hand, write operations to a data lake generally involve receiving the output data resulting from transformations performed by the engine, distributing and grouping the data according to the specified configurations, converting it into the desired data format to generate the output files based on those configurations, and finally persisting them in storage.
Understanding the importance of table structure and the operations performed by the process helps identify potential performance and cost issues depending on the instructions given to the query engines, in this case, DuckDB and ChDB.
The small files problem occurs when there are too many small files to process, resulting in a significant overhead of I/O operations and processing across multiple tasks within the pipeline, such as file selection, file opening, and metadata retrieval. This increases the overall operation latency.
On the other hand, the large files problem occurs when there are only a few files, but each one is considerably large. Although this reduces the number of I/O operations, depending on the table structure, it can limit the use of parallelism during execution, require more RAM to process the data efficiently, and potentially lead to reading unnecessary data, wasting processing time.

As a data engineer or data architect, understanding everything discussed above, there is one key aspect to define when implementing this process, as it is relevant to both the solution and the overall data architecture: finding an optimal balance between how files are organized within the table according to access patterns, the size of the files, and the appropriate use of resources and configurations for read and write operations in the query engine.
This is where the impact on costs and performance is defined, both for the lightweight data pipeline and the data lake. The concrete manifestation of this impact depends on the AWS services used to implement the lightweight data pipeline and the data lake. Based on a popular choice of AWS services—S3 Tables/S3 Buckets combined with AWS Lambda—the key fundamental cost operations I mentioned can be summarized as follows:
1️⃣ Storage costs: How much data is stored in S3 Tables/S3 Buckets?
2️⃣ Storage requests: How many data retrieval, listing, and storage operations are performed, and what is their total cost within S3 Tables/S3 Buckets?
3️⃣ Data processing resources: What resource configuration and additional variables are required for AWS Lambda, considering their direct impact on cost generation?
This also highlights an important principle regarding costs and performance across the components of a lightweight data pipeline:
📌 A data lake is a shared space between data producers, the data replicator that generates the data, and data consumers that consume it. Therefore, technical debt introduced by one component can affect a dependent component further downstream, increasing its costs if the right balance is not maintained between them.
This is why several best practices are generally recommended to help achieve this balance effectively:
  1. Apply appropriate data compression: Use a suitable compression algorithm to reduce file sizes based on the read and write workload. This affects storage costs as well as resource consumption in data processing services.
  1. Choose the right file size for the table: Maintaining a good distribution between the number of files and their individual sizes is important, as this affects the number of operations performed against storage and the resource consumption of data processing services. Generally, recommended file sizes range from 64 MB or 128 MB to 256 MB.
  1. Partition the data in the table: To avoid reading unnecessary data, the table structure should be organized according to the most common access patterns. This affects both resource consumption in data processing services and the number of operations performed against storage.
There is a fourth recommended practice: choosing the right data format for the data lake. Depending on the format, processing resources can be used more efficiently according to the table's purpose, as can storage resources within the data lake. However, this aspect is somewhat "already addressed" because the three popular data replication use cases are already oriented toward specific approaches within the data lake:
  • Delivering data to end consumers: JSON and CSV formats shine in this particular scenario because they are ready to be consumed through several important channels, such as APIs, Excel, or simply downloaded as files.
  • Keeping data for transformations: Apache Iceberg is the format of choice, as it enables data management capabilities that help ensure the required data quality.
  • Maintaining a copy of data for transformations in other layers/data lakes: Apache Parquet is the appropriate choice for this scenario because it provides a format that is ready to be processed by downstream processing engines without requiring much additional complexity.



What We Know So Far and What We Are Evaluating

When analyzing the performance results from the previous article exclusively from a financial cost perspective, using the financial data generated in this  spreadsheet , we can see that each data format has a more cost-effective query engine. There is also a common pattern that we previously identified, which can be summarized in the following table.
Data Format
Most Cost-Effective Engine
Approximate Savings
Recommended RAM
CSV
ChDB
~34%–44%
768 MB–1536 MB
JSON
ChDB
~36%–49%
768 MB–1024 MB
Apache Parquet
DuckDB
~48%–53%
256 MB–768 MB
Apache Iceberg
DuckDB
~44%–56%
256 MB–768 MB
This shows that, beyond performance considerations, DuckDB is a great option for data ingestion and transformation workloads intended for analytical purposes, while ChDB is a better choice for delivering data for end-user consumption.
Now, from a "technical cost" / "technical debt" perspective for the same solutions, there are certain peculiarities we need to keep in mind regarding how each engine works, as well as how it was used throughout this article. Some of these aspects go against the data lake best practices we initially discussed.
With ChDB, a single file containing all the data is generally created, depending on the output format. For CSV or JSON, this is not necessarily a problem, since consumers may require a single file. However, when data is consumed through an API, file size, compression, and partitioning can affect the performance of data consumption. The only exception to this behavior is Apache Iceberg, where file generation is affected by the configuration of the  iceberg_insert_max_bytes_in_data_file  and  iceberg_insert_max_rows_in_data_file  parameters.
With DuckDB, the size of the generated files is defined by the  FILE_SIZE_BYTES  parameter. This introduces a trade-off between file size and RAM consumption, as larger values generally require more RAM from the AWS Lambda function. In the performance tests presented in the article, values ranging from 10 MB to 30 MB were used as practical limits to ensure feasibility. It is also important to keep in mind that the resulting file sizes are approximate, meaning that individual files may be slightly larger or smaller than the specified target.
To further illustrate how the number of files generated by DuckDB varies, we show below the output produced using a  FILE_SIZE_BYTES  value of 10 MB for some data formats and relatively small data volumes, running on an AWS Lambda function with 386 MB of RAM, of which 70% was allocated to the processing engine.
Data Format
JSON
CSV
Parquet
61 MB – 1 file
156 files
39 files
8 files
117 MB – 2 files
298 files
74 files
14 files
368 MB – 6 files
940 files
234 files
44 files
484 MB – 8 files
N/A
308 files
57 files
Based on the practical tests, these observations reveal significant and critical differences that can affect downstream consumers within the lightweight data pipeline due to how data is structured in the data lake. This leads to an important question:
🤔💭 How are costs and out-of-the-box performance affected when both engines produce outputs that are more aligned with the best practices we discussed?
To answer this question, we need to define how to apply these best practices across some of the scenarios and understand how costs and performance change for these solutions. To do so, I will apply these best practices to low and medium data volumes, as shown in the following table.
Data Volume
Compress Data
Expected File Size
61 MB and 117 MB
Yes
64 MB
61 MB and 117 MB
No
64 MB
368 MB and 484 MB
No
64 MB
368 MB and 484 MB
Yes
64 MB
733 MB, 807 MB, and 941 MB
No
64 MB
733 MB, 807 MB, and 941 MB
Yes
64 MB
This will apply to the JSON, CSV, and Apache Parquet data formats, since the resulting values may vary, potentially changing how data replication use cases are assigned to each engine. Apache Iceberg was excluded because both engines can work with S3 Tables, which automatically handles table structuring according to the specified configuration.
There are also some considerations and decisions you should be aware of regarding the experiments that will be replicated:
  • Standard compression algorithms will be used: ZSTD for Apache Parquet due to its high compression ratio, while GZIP will be used for JSON and CSV because it is widely supported by several query engines. Check each data engine to see which compression options are available.
  • A 64 MB file size was selected: As we already observed, increasing the  FILE_SIZE_BYTES  parameter causes DuckDB to consume memory more rapidly. For ChDB, the challenge is to partition the data correctly to achieve file sizes as close as possible to 64 MB using  PARTITION BY .
  • Partitioning was intentionally excluded: The reason is simple: once data is further segmented through partitioning, query optimization becomes more evident depending on the applied data access pattern. I believe data compression has a greater influence on the consumer's experience and can provide more meaningful insights into the improvements made to the process itself.



Applying Changes and Analyzing Results

Implementation and Review with DuckDB

The base code remains the same as the one used in the performance benchmarking article for the JSON, CSV, and Apache Parquet data formats. However, two important aspects have changed: the amount of RAM available to the process and the compression algorithm used. With these adjustments, the code looks as follows.
import time
import duckdb
import os
import shutil
import json
def log_metric(metric, value, **dimensions):
print(json.dumps({
"type": "BENCHMARK",
"metric": metric,
"value": value,
**dimensions
}))
def lambda_handler(event, context):
# Variables
TABLE_ORIGIN = event.get("TABLE_ORIGIN")
TABLE_DESTINY = event.get("TABLE_DESTINY")
MEMORY_LIMIT_MB = event.get("MEMORY_LIMIT_MB")
FILE_SIZE_BYTES = event.get("FILE_SIZE_BYTES")
PROCESS_EVENT = event.get("PROCESS_EVENT")
DESTINY_FORMAT = event.get("DESTINY_FORMAT")
DIMS = {"event_process": PROCESS_EVENT}
# Preparación de entorno
start = time.time()
os.makedirs("/tmp/duckdb_tmp", exist_ok=True)
print(duckdb.__version__)
con = duckdb.connect(database=':memory:')
con.execute(f"SET memory_limit = '{MEMORY_LIMIT_MB}MB';") ## Limite de memoria
con.execute("SET temp_directory='/tmp/duckdb_tmp';") ## Direccion dde
con.execute("SET threads = 1;")
con.execute("SET preserve_insertion_order = false")
end_setup = time.time()
log_metric("setup_time", end_setup - start, event_process = PROCESS_EVENT)
EXTENSIONS_DIR = "/opt/duckdb/extensions"
con.execute(f"SET extension_directory = '{EXTENSIONS_DIR}'")
# Cargar extensiones necesarias
con.execute("LOAD httpfs")
con.execute("LOAD parquet")
end_loading_extension = time.time()
log_metric("loading_extension", end_loading_extension - end_setup, event_process = PROCESS_EVENT)
# Query leyendo múltiples archivos parquet
query = f"""
COPY (
SELECT *
FROM read_parquet('s3://chdb-duckdb-lambda-datalake/TLC_Trip_Record_Data/source/{TABLE_ORIGIN}/*.parquet')
)
TO 's3://chdb-duckdb-lambda-datalake/TLC_Trip_Record_Data/target/DuckDB_best_practices/{DESTINY_FORMAT}/{TABLE_DESTINY}'
(
FORMAT {DESTINY_FORMAT},
FILE_SIZE_BYTES '{FILE_SIZE_BYTES}MB',
COMPRESSION ZSTD, --- como lo quieras usar: JSON/CSV -> GZIP & Parque ->t ZSTD
OVERWRITE_OR_IGNORE
);
"""
result = con.execute(query)
end_execution = time.time()
log_metric("query_execution", end_execution - end_loading_extension, event_process = PROCESS_EVENT)
# Cleaning process
con.close()
if os.path.exists("/tmp/duckdb_tmp"):
shutil.rmtree("/tmp/duckdb_tmp", ignore_errors=True)
end_cleaning = time.time()
log_metric("cleaning_execution", end_cleaning - end_execution, event_process = PROCESS_EVENT)
return {
"statusCode": 200
}
After running the tests with 70% of the available RAM allocated to the processing engine, the following charts show the overall AWS Lambda performance with DuckDB using compressed and uncompressed data formats.

There are several interesting findings when analyzing the charts, including the following:
📌 The baseline trends remain consistent: This includes the growth in execution time across data formats, the use of memory to improve performance, DuckDB's better performance with Parquet compared to CSV and JSON, and the percentage of time spent in each activity stage within AWS Lambda.
🔔 The minimum RAM requirement changed: The process now starts with 512 MB of AWS Lambda memory because the  FILE_SIZE_BYTES  parameter needed to be set to 64 MB to achieve the target file size. The upside is that fewer files need to be accessed!
✨ Data compression affects performance differently across formats: When compared against their uncompressed counterparts, Apache Parquet experiences an average execution time increase of approximately 3% to 16%. CSV increases by approximately 153% to 197%, while JSON increases by approximately 34% to 65%.
✨ Data compression has a significant impact on storage requirements: Each format behaves differently when comparing compressed and uncompressed versions. Apache Parquet achieves an approximate 25% to 27% reduction in storage size through compression. Since JSON and CSV generate larger data volumes due to their verbose formats, compression reduces CSV data volume by approximately 81%, while JSON achieves an even greater reduction of approximately 94%.
When generating output files, the processes also exhibit some interesting behaviors, which are summarized in the following image.

💸 Processing costs confirm what we already know: DuckDB is more cost-efficient when working with Apache Parquet than with CSV and JSON, since the latter two formats require more RAM to process. Based on a simulation of 10,000 executions, the estimated costs would be as follows, using the values from our experiments.

💸 Storage costs confirm what we already know about the service: Storage capacity has a greater impact on costs than the number of write operations. Read operations can also become relevant when the data lake has any of the issues discussed earlier, although that is not the case in this experiment.
If I had to establish a priority order for reviewing storage-related costs, it would be the following:
  1. Storage volume.
  1. Read operations against the source.
  1. Write operations to the destination.
Considering write operations and storage costs with a retention period of one month, the following simulation shows the estimated monthly costs for 10,000 executions of this data processing operation.

When comparing the costs of the compressed and uncompressed versions, we can see that Apache Parquet achieves approximate cost savings of 22% to 24%, CSV saves around 70%, and JSON achieves savings of approximately 90% to 91%.
📌 Managing compression was straightforward: It only required adding one additional line to the SQL query section of the existing code, making it configurable.
🚨 Consider the impact on timeouts and Out-of-Memory errors: Data compression increases the likelihood of encountering these types of failures. For Apache Parquet, the 512 MB RAM configuration experienced more Out-of-Memory errors than the 768 MB configuration. This happens because processing larger data volumes requires more RAM, as illustrated by the memory consumption charts from the experiments.

The Out-of-Memory and/or timeout behavior observed with CSV and JSON remains consistent with the results presented in the performance benchmarking article.

Implementation and Review with ChDB

This solution has a serious problem: there is no easy way to generate files with a specific target size. For CSV, JSON, and Apache Parquet, there is no straightforward solution. Therefore, after analyzing the available options, there are two approaches we can take to achieve an approximate implementation:
  1. Use the  PARTITION BY  clause to generate files that are as close as possible to the expected size by controlling the number of output files to be generated.
  1. Use the  send_query  function to retrieve a specific number of records, allowing the record count to approximate the expected file size and generate the desired output files in streaming mode.
Both approaches require additional work: manually estimating either the number of files needed based on the target file size or the number of records required to achieve a specific data volume. This also requires additional metadata about the data volume to generate files as close as possible to the expected size.
The base code for the first approach is very similar to the one used in the performance benchmarking article for JSON, CSV, and Apache Parquet. However, there are now two key differences in the implementation:
  1.  PARTITION BY  becomes the foundation of the process.
  1. The process has been made more generic to accommodate different execution scenarios.
Remember that editing the code directly in AWS Lambda is not an option because, due to ChDB's package size, the function must be deployed as a container image.
The code implementing this approach is shown below:
import chdb
import logging
import os
import time
import json
import shutil

def log_metric(metric, value, **dimensions):
print(json.dumps({
"type": "BENCHMARK",
"metric": metric,
"value": value,
**dimensions
}))
def lambda_handler(event, context):
PROCESS_EVENT = event.get("PROCESS_EVENT")
start = time.time()
### Preparing workspace
DB_PATH = "/tmp/chdb_database"
os.makedirs(DB_PATH, exist_ok=True)
CONN = chdb.connect(DB_PATH)
end_setup = time.time()
log_metric("setup_time", end_setup - start, event_process = PROCESS_EVENT)
source = event["TABLE_ORIGIN"]
target = event["TABLE_DESTINY"]
output_format_sql = event["OUTPUT_FORMAT"]
memory_mb = int(event.get("MEMORY_LIMIT_MB", 256))
memory_bytes = memory_mb * 1024 * 1024
### Compresión: ZSTD para Parquet (interna), GZIP para CSV/JSON
compress = str(event.get("COMPRESS", False)).lower() in ("true", "1", "yes")
fmt = output_format_sql.lower()
is_parquet = "parquet" in fmt
s3_extra_args = ""
parquet_setting = ""
if is_parquet:
parquet_setting = f",\n output_format_parquet_compression_method = '{'zstd' if compress else 'none'}'"
extension = ".zstd.parquet" if compress else ".parquet"
else:
base_ext = ".json" if "json" in fmt else ".csv" if "csv" in fmt else f".{fmt}"
if compress:
# s3(path, format, structure, compression): la estructura va en 'auto' antes de la compresión
s3_extra_args = ", 'auto', 'gzip'"
extension = f"{base_ext}.gz"
else:
extension = base_ext
### Nombre final: se quita la extensión que traiga el destino y se pone la correcta
for old_ext in (".zstd.parquet", ".csv.gz", ".json.gz", ".parquet", ".csv", ".json", ".gz"):
if target.lower().endswith(old_ext):
target = target[: -len(old_ext)]
break
### Particionado en N archivos
num_files = int(event.get("NUM_FILES", 1))
partition_sql = ""
if num_files > 1:
if "{_partition_id}" not in target:
target = f"{target}_{{_partition_id}}"
partition_sql = f"PARTITION BY rowNumberInAllBlocks() % {num_files}"
target = f"{target}{extension}"
### Processing core
sql = f"""
INSERT INTO FUNCTION s3(
'{target}',
'{output_format_sql}'{s3_extra_args}
)
{partition_sql}
SELECT *
FROM s3('{source}', 'Parquet')
SETTINGS
max_memory_usage = {memory_bytes},
max_threads = 1,
max_insert_threads = 1,
max_block_size = 8192,
s3_truncate_on_insert = 1{parquet_setting}
"""
CONN.query(sql)
end_execution = time.time()
log_metric("query_execution", end_execution - end_setup, event_process = PROCESS_EVENT)
CONN.close()
### Cleaning workspace
if os.path.exists("/tmp/chdb_database"):
shutil.rmtree("/tmp/chdb_database", ignore_errors=True)
return {
"status": "SUCCESS",
"target": target
}
During testing, I identified a critical issue with the approach being used:
⚠️ Generating files with specific target sizes is resource-intensive. I reached this conclusion because, when attempting to increase the number of output files to achieve an approximate target size of 64 MB, the process encountered a  MEMORY_LIMIT_EXCEEDED  error, indicating that it required more RAM to accomplish this. Additionally, there is no guarantee that the generated files will actually reach the expected target size.
This makes generating multiple output files a delicate task, especially as the volume of data being processed increases.
Let's consider an example using a 368 MB dataset with an AWS Lambda function configured with 1536 MB of RAM, using Apache Parquet. By varying the number of output files required to achieve the desired file size in the uncompressed version, we obtain the following results, summarized in the table below.
Number of Output Files
RAM Consumption
Execution Time
Generated File Characteristics
2
1,045.8 MB
59.755 s
641.8 MB total, approximately 320.9 MB per file
3
1,530.0 MB
57.054 s
663.3 MB total, approximately 221.1 MB per file
6
Memory Limit Exceeded
Memory Limit Exceeded
Memory Limit Exceeded
This happens because ChDB opens an independent write process for each partition, resulting in higher RAM consumption due to the separate buffer allocated to each one.
Imagine increasing the data volume, the number of partitions, and/or using different data formats with this approach. It would become a cost issue. Based on these findings, I reached the following conclusion:
🚩 The approach based on  PARTITION BY  is not suitable for partitioning with ChDB on AWS Lambda.
The alternative approach is therefore to use streaming with  send_query  to generate independent files in the same location.
The main advantage of this approach is that it loads only a specific batch of records at a time instead of loading the entire dataset into RAM. This helps avoid Out-of-Memory issues while applying transformations to each stream, reducing overall latency.
The code implementing this approach is available  here , as it is too large to include directly in the article.
After running the tests with 80% of the available RAM allocated to the processing engine, a configuration selected to ensure execution feasibility for the engine, the following charts show the overall AWS Lambda performance with ChDB using compressed and uncompressed data formats.

There are several interesting findings from analyzing the charts and the experiment, including the following:
✨ It covers most of the test scenarios: This is mainly due to how ChDB manages data in batches to continue execution. This provides greater stability when processing different data volumes, even with the minimum resource configuration of 1024 MB of RAM for AWS Lambda with ChDB.
🚨 The main issue now is timeouts: I believe this happens because generating each output file takes longer depending on the number of records included in each batch to achieve the expected output file size. This potentially introduces a trade-off between file size, process performance, and the number of records processed per batch.
✨ Data compression affects performance differently across formats: When compared against their uncompressed counterparts, Apache Parquet experiences an average execution time increase of approximately 3% to 12%. CSV increases by approximately 132% to 186%, while JSON increases by approximately 26% to 67%.
✨ Data compression has a significant impact on storage requirements: Each format behaves differently when comparing compressed and uncompressed versions. Apache Parquet achieves an approximate storage reduction of 23% to 28% through compression. Since JSON and CSV generate larger data volumes due to their verbose formats, compression reduces CSV data volume by approximately 82% to 84%, while JSON achieves an even greater reduction of approximately 94% to 95%.
One interesting finding is that the compressed Apache Parquet version does not result in a smaller size when compared against the original data volume. This requires further investigation, as it could be related to the characteristics of the data itself or how the output file is generated.
When generating output files, the processes also exhibit some interesting behaviors, which are summarized in the following image.

✨ It is more memory-efficient compared to the code used in the first approach for generating files with a specific target size. This is because the RAM consumption growth curve is extremely shallow as the data volume increases, as shown in the chart.

The code can be further adapted to generate larger or smaller files as needed, which may lead to higher RAM consumption. This could become an interesting optimization area to explore.
I can now see that AWS Lambda configurations with 1024 MB to 1536 MB of RAM can be quite efficient for most data formats.
💡 The key lies in the number of data blocks to process, which is controlled through the  max_block_size  parameter. This determines the number of records in each batch, which are then accumulated until the target file size is approximately reached.
For CSV and Parquet, both compressed and uncompressed, a batch size of 8,192 records generates files ranging from 63.5 MB to 67.2 MB. However, with uncompressed JSON, files can easily reach 83.1 MB, which does not happen with its compressed counterpart. This makes selecting the appropriate batch size according to the transformation workload and data format an important aspect to evaluate.
💸 Processing costs reveal something interesting: The minimum RAM configuration is the cheapest option in most test scenarios, and the additional cost of increasing RAM does not appear to be justified by the observed memory consumption patterns.
The following chart presents a cost analysis focused exclusively on processing performance, based on a simulation of 10,000 executions, to explore the estimated cost of each scenario.

💸 Storage costs confirm what we already know: Storage capacity has a greater impact on costs than the number of write operations, and this also holds true for ChDB, just as it does for DuckDB. Storage accounts for approximately 95.5% to 98% of the total cost. Compressing data therefore makes a significant difference in long-term storage costs, making the additional AWS Lambda processing time justified in this scenario.
Considering write operations and storage costs with a one-month retention period, the following simulation shows the estimated monthly costs for 10,000 executions of this data processing operation.


In addition to everything discussed so far, there are two considerations regarding the code that you should keep in mind:
✨ It is efficient in terms of write operations: It minimizes the number of write operations performed because it does not use the S3 API's multipart upload mechanism, as is commonly done by default. Instead, it performs a single write operation for each generated file. It would also be worth exploring whether the writing process could be parallelized using threads to further improve performance.
⚠️ The code is difficult to manage when partitioning is required: This is because of how data is retrieved and subsequently written, while the entire implementation is still based on a single logical approach. Adding another layer of logic to handle partitioning could make the code more complex and potentially require additional reads over the same dataset to achieve the desired result.



Comparison from the Consumer's Perspective

With all the information gathered about these engines and the impact of best practices on their behavior, we need to answer an important question:
🤔💭 How does all of this affect the data lake consumer?
To simulate a data consumer workload in AWS Athena, I used the SQL queries  SELECT COUNT(1)  and  SELECT * , as these are representative queries commonly found in SQL-based data pipelines developed by data analysts.
By executing each query 30 times, we can obtain the following results, as shown in the charts below:


Based on these charts, we can confirm the following findings:
🧐 The cost difference between both engines is relatively small according to the experiments, ranging from approximately $0.002 to $0.07 in most cases. Therefore, the deciding factor between the two options will likely depend on how frequently consumers execute their queries and whether other aspects of the data architecture become more relevant when making the decision, such as implementation complexity or data producer costs.
💡 DuckDB is always the better option when it comes to minimizing the data volume generated. The only reasons to choose ChDB would be if DuckDB is not a viable solution under a given configuration, or if the cost of generating the output data volume outweighs the impact of how consumers query that data. This can be a challenging trade-off to evaluate.
✅ Compressing data is always more cost-efficient than leaving it uncompressed.
❗ Keep in mind that query results are stored in CSV format by AWS Athena, which may introduce additional costs for consumers.



Conclusion

We can now answer the question of which query engine is more cost-efficient from both a technical and financial perspective. The following table summarizes the key evaluation criteria and the conclusions reached for each one.
Key Criteria
Conclusion
Lower output data volume, compressed and uncompressed
DuckDB
Fewer output files
DuckDB for Parquet and CSV; chDB for uncompressed JSON
AWS Lambda execution speed
DuckDB for Parquet, but chDB for CSV and JSON
AWS Lambda processing costs
DuckDB for Parquet, but chDB for CSV and JSON
Text compression with large data volumes
chDB
Stability as data volume increases
chDB
Ease of code management when implementing best practices
DuckDB
Therefore, my recommendations for data replication in a data lake using AWS Lambda are as follows:
🔥 As a data producer: DuckDB is well suited for data transformation, while ChDB is a better fit for delivering data to end users. For large data volumes, ChDB is an ideal option.
🔥 As a data consumer: DuckDB is generally the better option because it generates smaller output data volumes.
🔥 Data compression is mandatory in the solution. Data partitioning should be evaluated according to the data access patterns.
With this, I conclude the discussion on lightweight data pipelines for data replication in a data lake. In the next edition, we will explore the data transformation process.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article