A transaction is a set of Datastore operations on one or more entities. Each transaction is guaranteed to be atomic, which means that transactions are never partially applied. Either all of the operations in the transaction are applied, or none of them are applied.
Transactions have a maximum duration of 60 seconds with a 10 second idle expiration time after 30 seconds.
An operation may fail when:
- Too many concurrent modifications are attempted on the same entity group.
- The transaction exceeds a resource limit.
- The Datastore encounters an internal error.
In all these cases, the Datastore API returns an error.
Transactions are an optional feature of the Datastore; you're not required to use transactions to perform Datastore operations.
An application can execute a set of statements and Datastore operations in a single transaction, such that if any statement or operation raises an exception, none of the Datastore operations in the set are applied. The application defines the actions to perform in the transaction.
The following snippet shows how to perform a transaction using the Datastore API. It transfers money from one account to another.
Note that in order to keep our examples more succinct we sometimes omit the
rollback if the transaction fails. In production code it is important to ensure that every transaction is either explicitly committed or rolled back.
What can be done in a transaction
All Datastore operations in a transaction can operate on a maximum of twenty-five entity groups. This includes querying for entities by ancestor, retrieving entities by key, updating entities, and deleting entities.
When two or more transactions simultaneously attempt to modify entities in one or more common entity groups, only the first transaction to commit its changes can succeed; all the others will fail on commit. Because of this design, using entity groups limits the number of concurrent writes you can do on any entity in the groups. When a transaction starts, Datastore uses optimistic concurrency control by checking the last update time for the entity groups used in the transaction. Upon commiting a transaction for the entity groups, Datastore again checks the last update time for the entity groups used in the transaction. If it has changed since our initial check, an error is returned. For an explanation of entity groups, see Ancestor paths.
Isolation and consistency
Outside of transactions, the Datastore's isolation level is closest to read committed. Inside of transactions, serializable isolation is enforced. This means that another transaction cannot concurrently modify the data that is read or modified by this transaction. Read the serializable isolation wiki and the Transaction Isolation article for more information on isolation levels.
In a transaction, all reads reflect the current, consistent state of the Datastore at the time the transaction started. Queries and lookups inside a transaction are guaranteed to see a single, consistent snapshot of the Datastore as of the beginning of the transaction. Entities and index rows in the transaction's entity group are fully updated so that queries return the complete, correct set of result entities, without the false positives or false negatives described in Transaction Isolation that can occur in queries outside of transactions.
This consistent snapshot view also extends to reads after writes inside transactions. Unlike with most databases, queries and gets inside a Datastore transaction do not see the results of previous writes inside that transaction. Specifically, if an entity is modified or deleted within a transaction, a query or lookup returns the original version of the entity as of the beginning of the transaction, or nothing if the entity did not exist then.
Uses for transactions
One use of transactions is updating an entity with a new property value relative to its current value. The
transferFunds example above does
that for two entities, by withdrawing money from one account and transferring it
to another. The Google Cloud Datastore API does not automatically retry
transactions, but you can add your own logic to retry them, for instance to
handle conflicts when another request updates the same entity at the same time.
This requires a transaction because the value of
balance in an entity may be updated by another user after this code fetches the object, but before it saves the modified object. Without a transaction, the user's request uses the value of
balance prior to the other user's update, and the save overwrites the new value. With a
transaction, the application is told about the other user's update.
Another common use for transactions is to fetch an entity with a named key, or create it if it doesn't yet exist (this example builds on the TaskList example from creating an entity):
As before, a transaction is necessary to handle the case where another user is attempting to create or update an entity with the same string ID. Without a transaction, if the entity does not exist and two users attempt to create it, the second overwrites the first without knowing that it happened.
When a transaction fails, you can have your app retry the transaction until it succeeds, or you can let your users deal with the error by propagating it to your app's user interface level. You do not have to create a retry loop around every transaction.
Finally, you can use a transaction to read a consistent snapshot of the Datastore. This can be useful when multiple reads are needed to render a page or export data that must be consistent. These kinds of transactions are often called read-only transactions, since they perform no writes. Read-only single-group transactions never fail due to concurrent modifications, so you don't have to implement retries upon failure. However, multi-entity-group transactions can fail due to concurrent modifications, so these should have retries.
Transactions and entity groups
An entity group is a set of entities connected through ancestry to a common root element. The organization of data into entity groups can limit what transactions can be performed:
- All the data accessed by a transaction must be contained in at most 25 entity groups.
- If you want to use queries within a transaction, your data must be organized into entity groups in such a way that you can specify ancestor filters that will match the right data.
- There is a write throughput limit of about one transaction per second within a single entity group. This limitation exists because Datastore performs masterless, synchronous replication of each entity group over a wide geographic area to provide high reliability and fault tolerance.
In many applications, it is acceptable to use eventual consistency (i.e. a non-ancestor query spanning multiple entity groups, which may at times return slightly stale data) when obtaining a broad view of unrelated data, and then to use strong consistency (an ancestor query, or a
lookup of a single entity) when viewing or editing a single set of highly related data. In such applications, it is usually a good approach to use a separate entity group for each set of highly related data.
For more information, see Data Consistency.