Parquet is a popular columnar file format used in data engineering, analytics, reporting, and large-scale data processing. It is designed to store structured data efficiently while reducing storage requirements and improving query performance. However, working with large Parquet files in a .NET application can become challenging when developers try to load the entire dataset into memory before processing it.

For example, imagine an application that needs to process several million transaction records stored in a Parquet file. Loading every record into a List or DataTable can consume a significant amount of memory. It can also increase garbage collection activity and affect the performance of other operations running in the application.

C# developers can avoid this problem by processing Parquet files in smaller sections using row groups and column-based operations. Instead of loading the complete dataset, an application can read one row group, process the required columns, release the temporary data, and continue with the next group.

In this article, we will explore how to read and write Parquet files using C# without loading the entire dataset into memory. We will also cover practical implementation examples, memory management considerations, common mistakes, and production best practices.

Understanding the Parquet File Format

Parquet is a column-oriented storage format. Unlike CSV files, which generally store values row by row, Parquet organizes data by columns and divides the file into row groups.

Consider a transaction dataset containing the following columns:

TransactionId

CustomerName

Amount

TransactionDate

101

Rahul

1500

2026-01-10

102

Priya

2500

2026-01-11

103

Amit

1800

2026-01-12

In a row-oriented format, the values belonging to each transaction are stored together. In Parquet, values belonging to the same column are stored together within the file's column chunks.

This structure provides several advantages when applications need to analyze specific columns. For example, a reporting service that only needs TransactionId and Amount does not need to decode CustomerName and TransactionDate.

Parquet also supports compression and encoding techniques that can reduce storage requirements.

What Are Row Groups?

A row group is a logical horizontal partition of rows inside a Parquet file. Each row group contains one column chunk for each column in the schema.

For example, a file containing 100,000 records might be organized into multiple row groups:

Row Group

Records

Row Group 1

10,000

Row Group 2

10,000

Row Group 3

10,000

Row Group 4

10,000

Remaining groups

60,000

An application can process these groups individually rather than loading all 100,000 records together.

The important point is that row groups provide a practical boundary for controlling how much data is decoded and held in memory at one time.

Setting Up Parquet Support in a C# Application

For this implementation, we will use Parquet.Net, a .NET library that supports reading and writing Apache Parquet files. It provides low-level APIs that allow developers to work directly with schemas, columns, and row groups.

The low-level API is useful when memory usage matters because it gives the application control over which columns to read and when to process each row group.

Installing the Required Package

Create a new console application:

Bash
dotnet new console -n ParquetProcessing
cd ParquetProcessing

Install the Parquet.Net NuGet package:

Bash
dotnet add package Parquet.Net

The examples below use the modern asynchronous API available in the 6.x release line and target a supported modern .NET runtime.

The main types we will use are:

  • ParquetReader: Opens an existing Parquet file.

  • ParquetWriter: Creates a new Parquet file.

  • ParquetSchema: Defines the structure of the file.

  • DataField: Represents a column in the schema.

  • ParquetRowGroupReader: Reads data from an individual row group.

  • ParquetRowGroupWriter: Writes data into a row group.

Reading a Large Parquet File Without Loading Everything Into Memory

One of the most important decisions when processing a large Parquet file is how much data the application reads at once.

A common mistake is to deserialize the entire file into a collection of C# objects. Although this approach is convenient for smaller datasets, it becomes expensive when the file contains millions of records.

Instead, we can open the file, inspect its schema, and process each row group independently.

Reading Data Row Group by Row Group

Consider a transaction file containing the following fields:

  • TransactionId

  • CustomerName

  • Amount

  • TransactionDate

We want to calculate the total transaction amount without storing every transaction in a collection.

The following example demonstrates how to read one row group at a time.

C#
using Parquet;
using Parquet.Schema;

public static async Task ProcessTransactionsAsync(
    string filePath,
    CancellationToken cancellationToken = default)
{
    decimal totalAmount = 0;

    await using ParquetReader reader =
        await ParquetReader.CreateAsync(filePath);

    DataField[] fields = reader.Schema.GetDataFields();

    DataField transactionIdField =
        fields.First(f => f.Name == "TransactionId");

    DataField amountField =
        fields.First(f => f.Name == "Amount");

    for (int groupIndex = 0;
         groupIndex < reader.RowGroupCount;
         groupIndex++)
    {
        cancellationToken.ThrowIfCancellationRequested();

        using ParquetRowGroupReader groupReader =
            reader.OpenRowGroupReader(groupIndex);

        int rowCount = checked((int)groupReader.RowCount);

        int?[] transactionIds = new int?[rowCount];
        decimal?[] amounts = new decimal?[rowCount];

        await groupReader.ReadAsync(
            transactionIdField,
            transactionIds.AsMemory(),
            null,
            cancellationToken);

        await groupReader.ReadAsync(
            amountField,
            amounts.AsMemory(),
            null,
            cancellationToken);

        for (int i = 0; i < rowCount; i++)
        {
            if (transactionIds[i].HasValue &&
                amounts[i].HasValue)
            {
                totalAmount += amounts[i]!.Value;
            }
        }

        Console.WriteLine(
            $"Processed row group {groupIndex + 1} " +
            $"containing {rowCount} records.");
    }

    Console.WriteLine($"Total transaction amount: {totalAmount}");
}

This implementation uses the low-level column reading API rather than converting the entire file into a collection.

Let's understand the important parts.

First, ParquetReader.CreateAsync opens the file and reads its metadata. The application can inspect the schema and row group count without immediately decoding every data column.

Next, the code identifies only the TransactionId and Amount fields. It does not read CustomerName or TransactionDate because they are not required for the calculation.

The application then loops through the available row groups. For each group, it creates arrays sized to that group's row count and reads the two required columns.

After processing the values, the arrays become eligible for garbage collection when they are no longer referenced. The application then moves to the next row group.

This approach keeps the working dataset limited to the selected columns in the current row group rather than the complete file.

Why Reading Only Required Columns Matters

Suppose a Parquet file contains 20 columns, but your reporting operation needs only three.

Reading all 20 columns creates unnecessary decoding work and additional memory allocations.

Column selection is particularly useful for:

  • Financial reporting applications.

  • Data migration tools.

  • Analytics pipelines.

  • Background data processing services.

  • Large-scale import and export operations.

One important detail is that the arrays still hold an entire selected column for the current row group. Therefore, row group size and the number of selected columns both influence peak memory usage.

Writing Large Parquet Files in Smaller Batches

Reading large files efficiently is only one part of the problem. Writing large datasets can also cause memory pressure when an application collects every record before creating the output file.

For example, consider an application that exports transaction records from a database. A common implementation first retrieves all records into a List and then writes the complete collection into a Parquet file.

This approach creates unnecessary memory pressure.

A better solution is to fetch records in batches and write each batch as a separate row group.

Defining the Parquet Schema

Before writing data, we need to define the file structure.

C#
using Parquet;
using Parquet.Schema;

var transactionIdField = new DataField<int>("TransactionId");
var customerNameField = new DataField<string>("CustomerName");
var amountField = new DataField<decimal>("Amount");

var schema = new ParquetSchema(
    transactionIdField,
    customerNameField,
    amountField);

The schema defines the columns and their data types. Every row group written to the same file must follow this schema.

Writing Data in Batches

The following example demonstrates how to write multiple batches into one Parquet file.

C#
using Parquet;
using Parquet.Schema;

public record Transaction(
    int TransactionId,
    string CustomerName,
    decimal Amount);

public static async Task WriteTransactionsAsync(
    IEnumerable<Transaction> transactions,
    string outputPath,
    CancellationToken cancellationToken = default)
{
    var idField = new DataField<int>("TransactionId");
    var nameField = new DataField<string>("CustomerName");
    var amountField = new DataField<decimal>("Amount");

    var schema = new ParquetSchema(
        idField,
        nameField,
        amountField);

    const int batchSize = 5000;

    await using var fileStream = new FileStream(
        outputPath,
        FileMode.Create,
        FileAccess.Write,
        FileShare.None);

    await using ParquetWriter writer =
        await ParquetWriter.CreateAsync(
            schema,
            fileStream,
            cancellationToken: cancellationToken);

    var batch = new List<Transaction>(batchSize);

    foreach (Transaction transaction in transactions)
    {
        cancellationToken.ThrowIfCancellationRequested();

        batch.Add(transaction);

        if (batch.Count >= batchSize)
        {
            await WriteBatchAsync(
                writer,
                batch,
                idField,
                nameField,
                amountField);

            batch.Clear();
        }
    }

    if (batch.Count > 0)
    {
        await WriteBatchAsync(
            writer,
            batch,
            idField,
            nameField,
            amountField);
    }
}

private static async Task WriteBatchAsync(
    ParquetWriter writer,
    List<Transaction> batch,
    DataField<int> idField,
    DataField<string> nameField,
    DataField<decimal> amountField)
{
    using ParquetRowGroupWriter groupWriter =
        writer.CreateRowGroup();

    await groupWriter.WriteAsync(
        idField,
        batch.Select(x => x.TransactionId).ToArray().AsMemory());

    await groupWriter.WriteAsync(
        nameField,
        batch.Select(x => x.CustomerName).ToArray().AsMemory());

    await groupWriter.WriteAsync(
        amountField,
        batch.Select(x => x.Amount).ToArray().AsMemory());
}

The implementation uses a batch size of 5,000 records. Once the batch reaches that limit, the application creates a row group and writes its columns.

The important part is that the application does not need to keep all exported transactions in memory.

The WriteBatchAsync method creates a separate row group for each batch. The arrays passed to WriteAsync contain only the current batch's values.

After writing the batch, the list is cleared so that it can be reused for the next set of records.

For production applications, the IEnumerable input should ideally come from a database reader or another source that itself produces records incrementally. Passing an already materialized list containing millions of records would defeat the purpose of this approach.

Processing Database Records Directly Into Parquet

In production applications, data often comes from databases rather than existing collections.

For example, an export service may retrieve millions of records from SQL Server or PostgreSQL. Loading all database records into memory before writing them to Parquet introduces the same problem we are trying to avoid.

A better approach is to use a database reader and process records incrementally.

The following example demonstrates the general pattern using ADO.NET:

C#
await using var command = connection.CreateCommand();

command.CommandText = """
    SELECT TransactionId, CustomerName, Amount
    FROM Transactions
    ORDER BY TransactionId
    """;

await using var dbReader = await command.ExecuteReaderAsync(
    cancellationToken);

while (await dbReader.ReadAsync(cancellationToken))
{
    var transaction = new Transaction(
        dbReader.GetInt32(0),
        dbReader.GetString(1),
        dbReader.GetDecimal(2));

    batch.Add(transaction);

    if (batch.Count == batchSize)
    {
        await WriteBatchAsync(
            writer,
            batch,
            idField,
            nameField,
            amountField);

        batch.Clear();
    }
}

After the database reader finishes, write any remaining records in the final batch.

This pattern creates a continuous data processing pipeline:

Database → Data Reader → Batch → Parquet Row Group

For large exports, this is generally more practical than retrieving the complete database result into a List.

For reliable production exports, also consider database transaction isolation, command timeouts, cancellation, and the effect of long-running queries on database resources.

Comparing Different Parquet Processing Approaches

C# developers can use different approaches depending on the size of the dataset and the requirements of the application.

Approach

Memory Usage

Performance Considerations

Suitable Scenario

Deserialize entire file

High

Convenient for small files

Small datasets

Process row groups

Controlled by row group size

Good control over memory

Large datasets

Read selected columns

Lower when fewer columns are required

Avoids unnecessary column decoding

Reporting and analytics

Write in batches

Controlled by batch size

Avoids collecting all records

Large data exports

DataFrame-based processing

Depends on complete DataFrame size

Convenient for analysis

In-memory analytics

For large Parquet files, row-group processing and selected-column reading are generally preferable when the application needs predictable memory usage.

Advantages and Disadvantages of Row Group Processing

Advantages

  1. Lower memory consumption: The application processes a limited portion of the dataset at a time instead of creating one large collection.

  2. Better column selection: Developers can read only the columns required for a particular operation.

  3. Improved scalability: The same processing logic can handle files containing significantly more records without requiring the entire dataset to fit in memory.

  4. Better control: Developers can control batch sizes, cancellation, and processing boundaries.

  5. Flexible integration: The approach works well with database readers, background services, reporting applications, and data migration tools.

Disadvantages

  1. More implementation code: Developers must manage row groups, batches, schemas, and column types.

  2. Row group size matters: Large row groups can still consume substantial memory.

  3. Random access requirements: Parquet readers generally require a readable and seekable input stream. A non-seekable network stream cannot simply be passed directly to the reader.

  4. Schema compatibility: All row groups in a file must follow a compatible schema.

  5. Processing complexity: Nested fields, nullable values, and different Parquet data types require additional handling.

Best Practices for Production Applications

Processing Parquet files efficiently requires more than simply using row groups. Developers should also consider how data is retrieved, stored, and processed.

1. Choose an Appropriate Row Group Size

Do not select a row group size without considering the average record size and the number of columns.

A row group containing 5,000 records may be reasonable for one dataset but too large for another if its records contain large strings or complex nested structures.

Start with a manageable batch size, monitor memory consumption, and adjust it according to the actual data.

2. Read Only Required Columns

Avoid reading every column when the operation requires only a few fields.

This is particularly important for wide datasets containing customer information, transaction details, timestamps, and additional metadata.

Reducing the number of decoded columns can reduce memory usage and unnecessary processing.

3. Use Asynchronous Operations

Prefer asynchronous APIs such as CreateAsync, ReadAsync, and WriteAsync.

These APIs help applications avoid blocking threads while waiting for file operations to complete.

However, asynchronous execution does not automatically reduce memory consumption. Proper batching and resource management are still necessary.

4. Dispose Resources Properly

Parquet readers, writers, file streams, and row-group resources should have clearly defined lifetimes.

Use await using for asynchronous resources and ensure temporary row-group readers and writers are disposed after processing.

This helps avoid unnecessary file handles and resource retention.

5. Implement Cancellation Support

Large file operations may take several minutes or longer, depending on file size and processing requirements.

Pass CancellationToken through the processing pipeline and check it between row groups or batches.

This is particularly useful for ASP.NET Core applications and background workers where users or administrators may need to stop an operation.

6. Avoid Excessive Parallel Processing

Processing multiple row groups simultaneously may appear attractive, but it can increase memory consumption because multiple groups may remain in memory at the same time.

Start with sequential processing. Introduce bounded parallelism only after measuring the workload and confirming that additional memory and I/O capacity are available.

7. Validate Output Files

A file should not be treated as successfully exported simply because the writing loop completed.

Dispose the Parquet writer successfully so that the file metadata and footer are finalized. Consider writing to a temporary file first and moving it to its final location only after the export completes successfully.

This prevents incomplete exports from being mistaken for valid output files.

Common Mistakes When Working With Large Parquet Files

Common Mistake

Why It Causes Problems

Recommended Solution

Deserializing the complete file

Creates large in-memory collections

Process row groups individually

Reading unnecessary columns

Adds decoding work and allocations

Select required fields

Using very large batches

Increases peak memory usage

Adjust batch size

Keeping processed records in a List

Prevents memory from being released

Process and discard each batch

Ignoring nullable fields

Can cause incorrect data handling

Use nullable types where required

Assuming every stream is supported

Parquet reading requires seeking

Use a seekable stream or local staging file

Ignoring cancellation

Operations may continue unnecessarily

Pass CancellationToken

Writing incomplete output directly to its final location

Failed exports may leave unusable files

Use temporary output and validate completion

Troubleshooting Common Problems

OutOfMemoryException While Reading Parquet Files

This usually happens when an application reads too many columns, processes very large row groups, or stores previously processed records in a collection.

Start by reducing the number of selected columns and reviewing the row group size. Also check whether the application is accidentally retaining references to previously processed data.

Invalid Parquet File or Metadata Errors

These errors may occur when a file is incomplete, corrupted, or generated incorrectly.

Verify that the previous writing operation completed successfully and that the Parquet writer was properly disposed.

Also check whether the file was fully transferred before attempting to read it.

Schema or Data Type Mismatch

A Parquet file may contain nullable fields, different numeric types, or nested structures that do not match the application's assumptions.

Inspect the schema before processing the data. Avoid relying on column positions when the application can identify columns by their names and expected types.

Memory Usage Continues to Increase

If memory usage increases throughout processing, check whether records are being accumulated in a List, whether background tasks are retaining references, or whether multiple row groups are being processed concurrently.

Remember that garbage collection does not guarantee an immediate reduction in the memory reported by the operating system. Monitor managed heap usage and allocation behavior rather than relying only on process memory.

Summary

Reading and writing large Parquet files in C# does not require loading the complete dataset into memory. By using Parquet.Net and its low-level APIs, developers can process data in smaller row groups and select only the columns required for their operations.

When reading, the application can open a Parquet file, inspect its schema, process one row group at a time, and release temporary data before moving forward. When writing, records can be retrieved from databases or other sources in batches and stored as separate row groups within a single Parquet file.

For production applications, the most important considerations are choosing an appropriate batch size, avoiding unnecessary column reads, managing resources correctly, supporting cancellation, and validating completed files.

These practices help developers build more reliable and memory-conscious data processing applications using C# and .NET.