Skip to content

Serialized buffer consumer for destination snowflake - #11071

Merged
Christophe Duong (ChristopheDuong) merged 27 commits into
chris/snowflake-staging-memory-consumptionfrom
chris/refactor-consumer-serialized-buffer
Mar 18, 2022
Merged

Christophe Duong (ChristopheDuong) merged 27 commits into
chris/snowflake-staging-memory-consumptionfrom
chris/refactor-consumer-serialized-buffer

Conversation

@ChristopheDuong

@ChristopheDuong Christophe Duong (ChristopheDuong) commented Mar 11, 2022 •

Copy link
Copy Markdown
Contributor

What

Following up on #10866, implement serialized buffering to make snowflake destination more scalable with memory usage when working with a large number of streams
Related issue #10591 but this is a POC on snowflake destination using s3 staging. Another PR would have to follow to generalize to all s3 based destinations (and all other destinations)

The problem here is that it needs to change more abstraction classes in the code...

How

  • Instead of buffering in List<AirbyteRecordMessage>, the BufferedStreamConsumer is now configurable with a different "strategy" where the buffer is a ByteArrayOutputStream or FileOutputStream instead.
  • Since we are buffering serialized data, it is also now possible to choose and apply compression (later we can apply encryption too, see Build Encryption logic for files being generated in destinations #10009)
  • the Buffering implementations will be able to easily switch out format between CSV, Avro, parquet etc (which differs from the previous S3CsvWriter, GcsAvroWriter classes etc from before

The hierarchy of class follows:

  • BufferedStreamConsumer: high-level class to dispatch to different implementations for a destination. This is the main entrypoint to buffer and consume Airbyte Message for destination connectors
  • RecordBufferingStrategy: Implementation of the strategy used to buffer data (List<AirbyteRecordMessage> or serialized OutputStream). We probably want to slowly migrate connectors to the serialized method in the long run
  • Only in the serialized buffering strategy, RecordBufferImplementation: is the actual implementation with specifics on the buffer format (where the buffer sits, in-memory or in file) and how the data is being serialized (csv, avro, json etc)

Recommended reading order

  1. x.java
  2. y.python

🚨 User Impact 🚨

Are there any breaking changes? What is the end result perceived by the user? If yes, please merge this PR with the 🚨🚨 emoji so changelog authors can further highlight this if needed.

Benchmark figures

NOTE: I am attaching some charts below, some are displayed as a "summary" of this PR impacts, but you can expand some little bullet points that are collapsed by default to visualize into more details.

Benchmark on 5 streams (need bigger buffers per stream)

With 2G of data transferred over 5 streams running using compressed disk buffer in 17 min

S3-staging-5_streams_40000_records_1024mb_gzip_disk_buffer

With 2G of data transferred over 5 streams running using uncompressed disk buffer in 27 min

S3-staging-5_streams_40000_records_1024mb_disk_buffer

Because I wanted to compare the disk approaches vs the in-memory approaches with the same size of buffers, I increased the in-memory buffer size to be equal (1G). Unfortunetaly, using the same max heap size is not doable with those settings...

With 2G of data transferred over 5 streams running using compressed in-memory buffer (using 1G of max heap size results into OOME crash)

S3-staging-5_streams_40000_records_1024mb_gzip_inmemory_buffer_crash

With 2G of data transferred over 5 streams running using compressed in-memory buffer in 32 min (larger max heap size of 2G required)

S3-staging-5_streams_40000_records_1024mb_gzip_inmemory_buffer_max2g

The following chart shows the stability in memory usage even though we are transferring a much larger size of data over a smaller number of streams (so each stream can compress more data in their buffers)

With 5G of data transferred over 5 streams running using compressed in-memory buffer (larger max heap size of 2G required)

S3-staging-5_streams_100000_records_1024mb_gzip_inmemory_buffer_max2g

Benchmark on 200 streams (needs more buffers since we'd need one per stream)

With 2G of data transferred over 200 streams running for 38min using compressed disk buffer

S3-staging-200_streams_1000_records_gzip_disk_buffer

With 2G of data transferred over 200 streams running for 41min using uncompressed disk buffer

S3-staging-200_streams_1000_records_1024mb_disk_buffer

With 2G of data transferred over 200 streams running for 51min using compressed in memory buffer (larger max heap size of 2G required)

S3-staging-200_streams_1000_records_1024mb_ gzip_inmemory_buffer_max2g

@github-actions github-actions Bot added the area/connectors Connector related issues label Mar 11, 2022
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 11, 2022 18:00 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 11, 2022 18:00 Inactive
@ChristopheDuong Christophe Duong (ChristopheDuong) changed the title Chris/refactor consumer serialized buffer Serialized buffer consumer for destination snowflake Mar 11, 2022
@ChristopheDuong
Christophe Duong (ChristopheDuong) changed the base branch from master to chris/snowflake-staging-memory-consumption March 11, 2022 18:02
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 11, 2022 21:43 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 11, 2022 21:43 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 08:28 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 08:28 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 09:11 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 09:11 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 21:34 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 21:34 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 21:39 Inactive
@ChristopheDuong
Christophe Duong (ChristopheDuong) temporarily deployed to more-secrets March 14, 2022 21:39 Inactive

void clear() throws Exception;

void registerFlushEventHook(VoidCallable onFlushEventHook);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: rename to registerFlushAllEventHook because this isn't called from flushWriter

@ChristopheDuong Christophe Duong (ChristopheDuong) Mar 16, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👌 I'm not sure if we would want one day a hook for single-stream flush to differentiate from FlushAll though...

It's probably a question for when we tackle better management of partial checkpointing and surfacing state messages per stream

throw new RuntimeException(e);
}
});
if (streamBuffer != null) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

under what conditions would streamBuffer be null? As far as I can tell, this only comes from io.airbyte.integrations.destination.s3.csv.CsvRecordBuffer#createFunction which never returns null

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

computeIfAbsent: If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
If the mapping function returns null, no mapping is recorded. If the mapping function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memoized result

Right, It should not send back null.
I'll add an exception for safety, but it shouldn't happen unless it's being misused in the code depending on the createFunction.

private InputStream inputStream;
private boolean isClosed;

protected BaseRecordBufferImplementation(final RecordBufferStorage bufferStorage, final boolean withCompression) throws Exception {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we going to add a withEncryption boolean here to support encryption?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess yes.

Maybe we should move them out of the constructor and have a dedicated .withCompression(boolean) or .withEncryption(enum algorithm) method instead?


private static final Logger LOGGER = LoggerFactory.getLogger(FileRecordBuffer.class);

// The per stream size limit is following recommendations from:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this limit also apply to other destinations or is this specific to snowflake?

@ChristopheDuong Christophe Duong (ChristopheDuong) Mar 15, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the moment it applies to all destinations using File buffers. But we could tune the limits differently per destination... (or even expose the settings to users in their spec.json which would replace the part_size field for S3 for example)

It seems BigQuery has much higher authorized limits:

CSV: Maximum file size - compressed 4 GB The size limit for a compressed CSV file is 4 GB.
CSV: Maximum file size - uncompressed 5 TB The size limit for an uncompressed CSV file is 5 TB.

From https://cloud.google.com/bigquery/quotas#load_jobs

But do we want to use more disk space on the worker to buffer bigger files?

ATM, I thought it would be fine to use the same "recommended" size limits as suggested by Snowflake as they seem reasonable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But do we want to use more disk space on the worker to buffer bigger files?
ATM, I thought it would be fine to use the same "recommended" size limits as suggested by Snowflake as they seem reasonable.

Note that even though the destination warehouse may allow bigger per file size limits.

This setting would potentially affect how much memory the connector may consume when uploading a large file to the stage area, see #10260 (comment)

hasFailed = true;
throw new RuntimeException(e);
} finally {
if (hasFailed) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a benefit to having a finally block instead of

try {
        <...>
        uploadManager.complete();
} catch (final Exception e) {
      LOGGER.error("Failed to load data into storage {}", bucketPath, e);
        uploadManager.abort();
       throw new RuntimeException(e);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've had issues where the uploadManager is never called with neither .abort() nor .complete() in the past. (due to some Exceptions (or Throwable?) not being caught?)

This resulted in threads being left open and idle and holding the JVM from exiting and thus a stuck sync.

So that's why I've been doing finally blocks instead...


@Override
protected void createWriter(final OutputStream outputStream) throws IOException {
csvPrinter = new CSVPrinter(new PrintWriter(outputStream, true, StandardCharsets.UTF_8), CSVFormat.DEFAULT);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we always using the same CsvFormat? Looks like we're using QuoteMode.ALL for GcsCsvWriter and AzureBlobStorageCsvWriter

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a withCsvFormat method to configure the writer options

final S3DestinationConfig s3Config) {
this.nameTransformer = nameTransformer;
this.s3Client = s3Client;
this.s3StorageOperations = new S3StorageOperations(nameTransformer, s3Client, s3Config);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm splitting the Staging related operations that are not SQL based into its own BlobStorageOperations (in the destination-s3). So I'm re-using these here to manipulate objects in the S3-based stage area.

@codecov

codecov Bot commented Mar 16, 2022 •

Copy link
Copy Markdown

Codecov Report

Merging #11071 (fa7874e) into chris/snowflake-staging-memory-consumption (56caac4) will not change coverage.
The diff coverage is n/a.

@@                             Coverage Diff                             @@
##           chris/snowflake-staging-memory-consumption   #11071   +/-   ##
===========================================================================
  Coverage                                       69.55%   69.55%           
===========================================================================
  Files                                              10       10           
  Lines                                            1626     1626           
===========================================================================
  Hits                                             1131     1131           
  Misses                                            495      495           

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 56caac4...fa7874e. Read the comment docs.

@tuliren Liren Tu (tuliren) left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fantastic!

I have one general suggestion. Currently, the naming of the interfaces and implementations are not very straightforward. I think they can be simplified as follows:

Category Current Proposal
Buffer storage RecordBufferStorage BufferStorage
FileRecordBuffer FileBufferStorage
InMemoryRecordBuffer InMemoryBufferStorage
Buffer strategy RecordBufferingStrategy BufferStrategy
DefaultRecordBufferingStragegy InMemoryBufferStrategy
Serialized buffer implementation RecordBufferImplementation SerializedBuffer
BaseRecordBufferImplementation BaseSerializedBuffer
CsvRecordBuffer CsvSerializedBuffer

The rationales are:

  1. Remove the common prefix Record-.
  2. It's better to embed the interface name in the implementation class name. In this way, it is easier to know what that implementation is by just looking at its name.
    • For example, FileRecordBuffer implements RecordBufferStorage, but its name can be confused with implementations like CsvRecordBuffer, which is actually very different. So renaming it to FileBufferStorage is probably better.
    • Following this rule may make the names boring. But I think in a way, boring names are good names, because they are consistent.
  3. RecordBufferImplementation can be confusing since it is an interface, but its name includes -Implementation. Since it is part of the serialized buffer strategy, I propose to name it as SerializedBuffer. It's possible though that there are more accurate and specific names than my proposal.

outputRecordCollector,
getDatabase(config),
new SnowflakeInternalStagingSqlOperations(getNamingResolver()),
getNamingResolver(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick. This is not related to this PR. But the getNamingResolver method seems useless. We can instead make namingResolver in AbstractJdbcDestination a projected variable, and reference namingResolver directly.

@ChristopheDuong

Christophe Duong (ChristopheDuong) commented Mar 18, 2022 •

Copy link
Copy Markdown
Contributor Author

/test connector=connectors/destination-snowflake

🕑 connectors/destination-snowflake https://github.com/airbytehq/airbyte/actions/runs/2003185758

@ChristopheDuong

Christophe Duong (ChristopheDuong) commented Mar 18, 2022 •

Copy link
Copy Markdown
Contributor Author

/test connector=connectors/destination-snowflake

🕑 connectors/destination-snowflake https://github.com/airbytehq/airbyte/actions/runs/2004057285

@ChristopheDuong
Christophe Duong (ChristopheDuong) merged commit 703d788 into chris/snowflake-staging-memory-consumption Mar 18, 2022
@ChristopheDuong
Christophe Duong (ChristopheDuong) deleted the chris/refactor-consumer-serialized-buffer branch March 18, 2022 14:25
@ChristopheDuong

Copy link
Copy Markdown
Contributor Author

I'm merging into the other PR (#10866) and will be publishing from there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/connectors Connector related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants