The last RavenDB feature of the year, bulk inserts
One of the most exciting new features that got into RavenDB 2.0 is the notion of bulk inserts. Unlike the “do batches in a loop” approach, we actually created an optimized approach and a hand crafted code path that reduce the time of the standard RavenDB saves (which does a lot, but come at a cost).
In particular, we made sure that we can parallelize the operation between the client and the server, so we don’t have to build the entire request in memory on the client and then wait for it all to be in memory on the server before we can start operation. Instead, we have a fully streamed operation from end to end.
Here is what the API looks like:
This uses a single request to the server to do all the work. And here are the results:
This API has several limitations:
- You must provide the id at the client side (in this case, generated via hilo).
- It can't take part of DTC transactions
- If you want updates, you need to explicitly state (other would throw).
- Put triggers will execute, but the AfterCommit will not.
- This bypass the indexing memory pre fetching layer.
- Changes() will not be raised for documents inserted using bulk-insert.
- There isn't a single transaction for the entire operation, rather, this is done in batches and each batch is transactional on its own.
This is explicitly meant to drop a very large number of records to RavenDB very fast, and it does this very well, typically an order of magnitude or more faster than the “batches in a loop” approach.
A note about the last limitation, though. The whole idea here it to reduce, as much as possible, the costs of actually doing a bulk insert. That means that we can’t keep a transaction of millions of item open. Instead, we periodically flush the transaction buffer throughout the process. Assuming the default batch size of 512 documents, that means that an error in one of those documents will result in the entire batch of 512 being rolled back, but will not roll back previously committed batches.
This is done to reduce transaction log size and to make sure that even during a bulk insert operation, we can index the incoming documents while they are being stream in.