DynamoDB: updateItem Only If It Already Exists
By default, update_item behaves like a no-op if the primary key doesn't exist in your table; it simply creates the item and applies the attribute changes. This is often convenient for "upsert" patterns where you want to ensure a record exists regardless of its prior state. However, there are scenarios where creating new items is a bug waiting to happen. Perhaps you are implementing a feature flag system where an absent flag should default to false, or you are managing inventory levels that must strictly persist only if the product has been provisioned.
If your application logic requires that an update operation fails gracefully when the target key is missing, relying on the standard update_item API is insufficient. You cannot pass a boolean flag to say "only update if present" within the native SDK calls. The standard approach involves an explicit read before a write, but this introduces latency and increases write capacity consumption.
Conditional Writes with Condition Expressions
The robust solution lies in leveraging DynamoDB's ConditionExpression parameter. This allows you to define a predicate that must evaluate to true for the operation to succeed. If the condition failsâbecause the item does not existâthe service returns a ConditionalCheckFailedException.
You can check for existence using the built-in attribute_exists function within your condition expression. The syntax is straightforward across all major SDKs. In the AWS CLI, the command looks like this:
aws dynamodb update-item \
--table-name YourTableName \
--key '{"PK": {"S": "user-123"}, "SK": {"S": "profile"}}' \
--update-expression "SET status = :val" \
--expression-attribute-values '{":val": {"S": "active"}}' \
--condition-expression "attribute_exists(PK)"
In this example, if the key user-123 with sort key profile does not exist in the table, the update-item call will fail immediately. You handle the resulting ConditionalCheckFailedException in your application code to execute your fallback logic (e.g., returning a 404 or creating a default item via a separate path).
Handling Exceptions in Application Code
The power of this approach is that it consolidates two potential steps into one atomic operation. Consider a Laravel application using the aws/aws-sdk-php client. Instead of querying first and then updating, you attempt the update with a condition:
$command = (new UpdateItemCommand($table->getTableData()))
->withConditionExpression('attribute_exists(#pk)')
->withUpdateExpression('SET #status = :val');
$request = new Aws\DynamoDB\DynamicKeyObject([
'PK' => $item['PK'],
'SK' => $item['SK']
]);
try {
$table->updateItem($command);
} catch (ConditionalCheckFailedException $e) {
// Handle the case where the item was not found
return response()->json(['error' => 'User profile not found'], 404);
}
This pattern ensures data consistency without the race conditions inherent in a "read-then-write" loop. If another process creates the item between your read and write, the conditional check would still catch it if you were checking attributes rather than just existence, but here we specifically guard against accidental creation of new records.
Trade-offs and Limitations
While this method prevents unintended item creation, it does introduce a specific failure mode: ConditionalCheckFailedException. Your application must be prepared to handle this exception explicitly. If your business logic requires the item to exist before proceeding, catching this exception and treating it as an error is usually the correct path.
There is also a performance consideration. While atomic, conditional writes still incur read/write capacity units. However, they eliminate the need for a separate GetItem call, which would consume additional read capacity. By combining the check and the update into a single request, you often reduce total throughput costs compared to the fetch-then-update pattern.
For more complex scenarios involving multiple attributes or compound keys, the attribute_exists function remains the standard mechanism for enforcing existence constraints within a write operation. If you require advanced transaction logic that involves multiple items or specific locking mechanisms, DynamoDB Transactions provide further isolation guarantees, but for simple existence checks, ConditionExpression is the most direct tool available.