| 1 | ## Query idempotence |
| 2 | |
| 3 | A query is *idempotent* if it can be applied multiple times without changing the result of the initial application. For |
| 4 | example: |
| 5 | |
| 6 | * `update my_table set list_col = [1] where pk = 1` is idempotent: no matter how many times it gets executed, `list_col` |
| 7 | will always end up with the value `[1]`; |
| 8 | * `update my_table set list_col = [1] + list_col where pk = 1` is not idempotent: if `list_col` was initially empty, |
| 9 | it will contain `[1]` after the first execution, `[1, 1]` after the second, etc. |
| 10 | |
| 11 | Idempotence matters for [retries](../retries/) and [speculative query executions](../speculative_execution/). The driver |
| 12 | will bypass those features if the [Statement#isIdempotent()][isIdempotent] flag is set to `false`, to ensure that the |
| 13 | statement does not get executed more than once. |
| 14 | |
| 15 | In most cases, you must set that flag manually. The driver does not parse query strings, so it can't infer it |
| 16 | automatically (except for statements coming from the query builder, see below). |
| 17 | |
| 18 | Statements start out as non-idempotent by default. You can override the flag on each statement: |
| 19 | |
| 20 | ```java |
| 21 | Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1"); |
| 22 | s.setIdempotent(true); |
| 23 | ``` |
| 24 | |
| 25 | The default is also configurable: if you want all statements to start out as idempotent, do this: |
| 26 | |
| 27 | ```java |
| 28 | // Make all statements idempotent by default: |
| 29 | cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true); |
| 30 | ``` |
| 31 | |
| 32 | Any statement on which you didn't call `setIdempotent` gets this default value. |
| 33 | |
| 34 | Bound statements inherit the flag from the prepared statement they were created from: |
| 35 | |
| 36 | ```java |
| 37 | PreparedStatement pst = session.prepare("SELECT * FROM users WHERE id = ?"); |
| 38 | // This cast is for backward-compatibility reasons. On 3.0+, you can do pst.setIdempotent(true) directly |
| 39 | ((IdempotenceAwarePreparedStatement) pst).setIdempotent(true); |
| 40 | |
| 41 | BoundStatement bst = pst.bind(); |
| 42 | assert bst.isIdempotent(); |
| 43 | ``` |
| 44 | |
| 45 | ### Idempotence in the query builder |
| 46 | |
| 47 | The [QueryBuilder] DSL tries to infer the `isIdempotent` flag on the statements it generates. The following statements |
| 48 | will be marked **non-idempotent**: |
| 49 | |
| 50 | * counter updates: |
| 51 | |
| 52 | ```java |
| 53 | update("mytable").with(incr("c")).where(eq("k", 1)); |
| 54 | ``` |
| 55 | * prepend, append or deletion operations on lists: |
| 56 | |
| 57 | ```java |
| 58 | update("mytable").with(append("l", 1)).where(eq("k", 1)); |
| 59 | delete().listElt("l", 1).from("mytable").where(eq("k", 1)); |
| 60 | ``` |
| 61 | * queries that insert the result of a function call or a "raw" string in a column (or as an element in a collection |
| 62 | column): |
| 63 | |
| 64 | ```java |
| 65 | update("mytable").with(set("v", now())).where(eq("k", 1)); |
| 66 | update("mytable").with(set("v", fcall("myCustomFunc"))).where(eq("k", 1)); |
| 67 | update("mytable").with(set("v", raw("myCustomFunc()"))).where(eq("k", 1)); |
| 68 | ``` |
| 69 | |
| 70 | This is a conservative approach, since the driver can't guess whether a function is idempotent, or what a raw string |
| 71 | contains. It might yield false negatives, that you'll have to fix manually. |
| 72 | |
| 73 | * lightweight transactions (see the next section for a detailed explanation): |
| 74 | |
| 75 | ```java |
| 76 | insertInto("mytable").value("k", 1).value("v", 2).ifNotExists(); |
| 77 | ``` |
| 78 | |
| 79 | If these rules produce a false negative, you can manually override the flag on the built statement: |
| 80 | |
| 81 | ```java |
| 82 | BuiltStatement s = update("mytable").with(set("v", fcall("anIdempotentFunc"))).where(eq("k", 1)); |
| 83 | |
| 84 | // False negative because the driver can't guess that anIdempotentFunc() is safe |
| 85 | assert !s.isIdempotent(); |
| 86 | |
| 87 | // Fix it |
| 88 | s.setIdempotent(true); |
| 89 | ``` |
| 90 | |
| 91 | |
| 92 | ### Idempotence and lightweight transactions |
| 93 | |
| 94 | As explained in the previous section, the query builder considers lightweight transactions as non-idempotent. This might |
| 95 | sound counter-intuitive, as these queries can sometimes be safe to execute multiple times. For example, consider the |
| 96 | following query: |
| 97 | |
| 98 | ``` |
| 99 | UPDATE mytable SET v = 4 WHERE k = 1 IF v = 1 |
| 100 | ``` |
| 101 | |
| 102 | If we execute it twice, the `IF` condition will fail the second time, so the second execution will do nothing and `v` |
| 103 | will still have the value 4. |
| 104 | |
| 105 | However, the problem appears when we consider multiple clients executing the query with retries: |
| 106 | |
| 107 | 1. `v` has the value 1; |
| 108 | 2. client 1 executes the query above, performing a a CAS (compare and set) from 1 to 4; |
| 109 | 3. client 1's connection drops, but the query completes successfully. `v` now has the value 4; |
| 110 | 4. client 2 executes a CAS from 4 to 2; |
| 111 | 5. client 2's transaction succeeds. `v` now has the value 2; |
| 112 | 6. since client 1 lost its connection, it considers the query as failed, and transparently retries the CAS from 1 to 4. |
| 113 | But since the column now has value 2, it receives a "not applied" response. |
| 114 | |
| 115 | One important aspect of lightweight transactions is [linearizability]: given a set of concurrent operations on a column |
| 116 | from different clients, there must be a way to reorder them to yield a sequential history that is correct. From our |
| 117 | clients' point of view, there were two operations: |
| 118 | |
| 119 | * client 1 executed a CAS from 1 to 4, that was not applied; |
| 120 | * client 2 executed a CAS from 4 to 2, that was applied. |
| 121 | |
| 122 | But overall the column changed from 1 to 2. There is no ordering of the two operations that can explain that change. We |
| 123 | broke linearizability by doing a transparent retry at step 6. |
| 124 | |
| 125 | If linearizability is important for you, you should ensure that lightweight transactions are appropriately flagged as |
| 126 | not idempotent. |
| 127 | |
| 128 | [isIdempotent]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html#isIdempotent-- |
| 129 | [setDefaultIdempotence]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setDefaultIdempotence-boolean- |
| 130 | [QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html |
| 131 | |
| 132 | [linearizability]: https://en.wikipedia.org/wiki/Linearizability#Definition_of_linearizability |