Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Persistence

Dynamoid provides a persistence interface modeled closely after Rails Active Record. Standard methods like new, save, create, update_attributes, delete, and destroy provide familiar lifecycle behavior—triggering validations and callbacks, tracking dirty attributes, and enforcing optimistic locking.

Beyond the standard in-memory lifecycle, Dynamoid provides a database-level interface that modifies items directly in DynamoDB without loading them first. This allows you to perform partial updates and upserts in a single request, execute atomic mutations (such as counter increments and set changes) without race conditions, and guard writes with condition expressions.

Code examples throughout this guide refer to this model:

class User
  include Dynamoid::Document

  field :name
  field :age, :integer
  field :tags, :set, of: :string
end

Note

For models with a composite primary key, class-level persistence methods (update, delete, update_fields, upsert, inc) accept the sort key as the second argument (for example, Model.delete(partition_key, sort_key)).

Core Operations

Dynamoid provides standard persistence methods for creating, updating, and deleting model instances in DynamoDB:

Creating Models

To initialize a model in memory without writing to DynamoDB, call new and then persist it with save:

user = User.new(name: 'Alice', age: 30)
user.new_record? # => true
user.persisted?  # => false

user.save # => true
user.new_record? # => false
user.persisted?  # => true

DynamoDB does not auto-generate primary keys. For a model with a string partition key (id by default), Dynamoid assigns a random UUID automatically when the model is saved if a value was not provided explicitly:

user.id # => "3a9f7216-4726-4aea-9fbc-8554ae9292cb"

To instantiate and persist a model in a single call, use create:

user = User.create(name: 'Alice', age: 30)

Both new and create accept a block to initialize attributes on the model instance:

user = User.create do |u|
  u.name = 'Alice'
  u.age = 30
end

To create multiple models at once while still running validations and callbacks for each one, pass an array of attribute hashes to create:

users = User.create(
  [
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 25 }
  ]
)

When inserting multiple items where validations and callbacks are not needed, use import to write items in batches instead of issuing a separate request per model:

users = User.import(
  [
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 25 }
  ]
)

Warning

Because Dynamoid only generates UUIDs for string partition keys, any non-string partition key must be populated explicitly.

Updating Models

To update an existing item, load the model, modify its attributes in memory, and call save:

user = User.find(user_id)
user.name = 'Alicia'
user.save

To update multiple attributes and save the model in a single call, use update_attributes:

user.update_attributes(name: 'Alicia', age: 31)

To load an item by its primary key, update its attributes, and save it in a single call, use Model.update:

user = User.update(user_id, name: 'Alicia', age: 31)

To reload attributes from DynamoDB using a consistent read, call reload:

user.reload

To update the updated_at timestamp directly in DynamoDB without writing unchanged attributes, call touch:

user.touch

Warning

DynamoDB does not allow modifying an item’s partition key or sort key once persisted. To change a key value, you must create a new item with the new key and delete the original item.

Deleting Models

To remove a loaded model from DynamoDB and run destroy callbacks, call destroy:

user = User.find(user_id)
user.destroy
user.destroyed? # => true
user.persisted? # => false

To remove a loaded model immediately without running callbacks, call delete:

user.delete
user.destroyed? # => true

To delete an item directly by its primary key without loading it into memory first, call Model.delete:

User.delete(user_id)

Pass an array of keys to delete multiple items in a batch:

User.delete([user_id_1, user_id_2, user_id_3])

Database-Level and Atomic Updates

Instead of loading an item into memory and saving it back, you can modify items directly in DynamoDB with a single request. This avoids unnecessary read requests and prevents race conditions when updating attributes, incrementing counters, or mutating sets.

To modify specific attributes on an existing item directly in DynamoDB and return the updated model (or nil if the item does not exist), use Model.update_fields:

user = User.update_fields(user_id, name: 'Alicia', age: 31)

When an item may or may not already exist, Model.upsert updates the item by primary key or creates a new one if it is missing:

user = User.upsert(user_id, name: 'Alice', age: 30)

For numeric counters, Model.inc atomically adjusts values in DynamoDB in a single request (pass a negative number to decrement):

User.inc(user_id, age: 1)
User.inc(user_id, age: -1)

On a loaded model instance, update and update! accept a block to combine low-level DynamoDB mutation actions in a single atomic request. Use set to assign attribute values and add to increment numbers or append elements to a set:

user.update! do |u|
  u.set(name: 'Alicia')
  u.add(age: 1, tags: %w[admin verified])
end

Within the block, use delete to remove specific elements from a set or to remove an attribute from the item altogether:

user.update! do |u|
  u.delete(tags: ['guest'])
  u.delete(:age)
end

update_fields, upsert, update, and update! all support conditional updates. To apply an update only when existing attributes in DynamoDB match expected values, pass an if: condition:

User.update_fields(user_id, { age: 31 }, if: { age: 30 })

To apply an update only when one or more attributes do not exist on the item yet, pass unless_exists::

User.update_fields(user_id, { age: 18 }, unless_exists: [:age])

Validations

Dynamoid allows you to validate the state of a model before it is written to DynamoDB using standard Rails validators—such as presence, numericality, inclusion, length, and format—as well as custom validation methods:

class User
  include Dynamoid::Document

  field :name
  field :age, :integer

  validates :name, presence: true
  validates :age, numericality: { greater_than_or_equal_to: 18 }
end

When a model is invalid, save and update_attributes return false without writing to DynamoDB, and create returns the unsaved model instance:

user = User.new(age: 15)
user.valid?               # => false
user.errors[:name]        # => ["can't be blank"]
user.errors.full_messages # => ["Name can't be blank", "Age must be greater than or equal to 18"]
user.save                 # => false

If you want an invalid model to raise an exception instead, use the bang counterparts (save!, create!, update_attributes!, and Model.update!):

user.save! # Raises Dynamoid::Errors::DocumentNotValid

To bypass validations when saving a model, pass validate: false:

user.save(validate: false) # => true

Note

Dynamoid does not support uniqueness validations (such as validates_uniqueness_of) because DynamoDB cannot enforce uniqueness on non-key attributes without scanning the entire table. Enforce uniqueness using dedicated lookup tables or DynamoDB transactions instead.

Dirty Attribute Tracking

Dynamoid tracks unsaved in-memory attribute changes on every model instance. Modifying an attribute marks it as dirty until the model is saved or reloaded, which lets you inspect pending modifications and allows save to send only modified attributes to DynamoDB:

user = User.create(name: 'Alice')
user.changed?      # => false
user.name_changed? # => false

user.name = 'Alicia'
user.changed?      # => true
user.name_changed? # => true
user.name_was      # => "Alice"
user.changes       # => { "name" => ["Alice", "Alicia"] }

In-place mutations on mutable Ruby objects—such as mutating strings with ! methods, adding or removing elements in a set or array, or updating keys inside a hash—are also detected automatically without reassigning the attribute:

user = User.create(name: 'Alice', tags: ['ruby'])

user.name.upcase!
user.tags << 'dynamodb'

user.name_changed? # => true
user.tags_changed? # => true

user.save

To explicitly flag an attribute as dirty before modifying it, call <attribute>_will_change!:

user.name_will_change!

When save completes, the model’s unsaved changes are cleared, and the recorded modifications become accessible through previous_changes and <attribute>_previously_changed? (useful inside after_save or after_update callbacks):

user.name = 'Alicia'
user.save

user.changed?                 # => false
user.name_previously_changed? # => true
user.previous_changes         # => { "name" => ["Alice", "Alicia"], "updated_at" => [...] }

To discard unsaved in-memory modifications and restore attributes to their persisted values without querying DynamoDB, call restore_attributes (or restore_<attribute>! for an individual attribute):

user.name = 'Temporary'
user.restore_attributes
user.name # => "Alicia"

Note

For custom field types, Dynamoid detects in-place mutations by comparing serialized values or by using #== when comparable: true is configured (see Change Detection).

Optimistic Locking

When multiple processes load the same item, modify it in memory, and save it back, the later save can silently overwrite changes made by the earlier process. Dynamoid supports optimistic locking to detect concurrent modifications and prevent lost updates.

To enable optimistic locking on a model, declare an integer field named lock_version:

class User
  include Dynamoid::Document

  field :name
  field :lock_version, :integer
end

When a new model is saved, Dynamoid initializes lock_version to 1. On every subsequent save, it increments lock_version by 1 and verifies that the item has not changed in DynamoDB since it was loaded. If another process modified or deleted the item in the meantime, the save fails and Dynamoid raises an exception:

user = User.find(user_id)
user_copy = User.find(user_id)

user.name = 'Alice'
user.save!

user_copy.name = 'Alicia'
user_copy.save! # Raises Dynamoid::Errors::StaleObjectError

To recover from a conflict, rescue Dynamoid::Errors::StaleObjectError, reload the model to fetch the latest attributes and lock_version, re-apply your changes, and retry:

begin
  user.age += 1
  user.save!
rescue Dynamoid::Errors::StaleObjectError
  user.reload
  retry
end

To disable optimistic locking for a specific item, set its lock_version to nil:

user.update_attributes(lock_version: nil)

Modifying Items with PartiQL

DynamoDB supports PartiQL, a SQL-compatible query language that allows inserting, updating, and deleting items using familiar SQL statements. Use execute_partiql to execute modifying statements directly against DynamoDB and return nil.

To insert a new item, execute an INSERT statement:

User.execute_partiql(
  "INSERT INTO #{User.table_name} VALUE { 'id': ?, 'name': ?, 'age': ? }",
  ['3a9f7216-4726-4aea-9fbc-8554ae9292cb', 'Alex', 28]
) # => nil

To modify attributes on an existing item, execute an UPDATE statement:

User.execute_partiql(
  "UPDATE #{User.table_name} SET age = ? WHERE id = ?",
  [29, '3a9f7216-4726-4aea-9fbc-8554ae9292cb']
) # => nil

To remove an item by its primary key, execute a DELETE statement:

User.execute_partiql(
  "DELETE FROM #{User.table_name} WHERE id = ?",
  ['3a9f7216-4726-4aea-9fbc-8554ae9292cb']
) # => nil

Unlike standard SQL, DynamoDB’s PartiQL UPDATE and DELETE are singleton operations: each statement operates on a single item and requires specifying its full primary key in the WHERE clause (partition key, and sort key if the table has a composite primary key).

Note

Dynamoid does not type-cast bind parameter values or convert them to DynamoDB’s underlying storage format; non-native types (such as :datetime or :date) must be passed in their stored representation (such as numeric Unix epoch timestamps or ISO 8601 strings). In PartiQL statements, the table name must equal DynamoDB’s table name (such as User.table_name).

Feedback

We encourage you to help improve the quality of this guide!

If you spot a typo, a factual error, or a section that is incomplete or could be explained more clearly, please verify the behavior against the master branch and submit a pull request editing the Markdown files in the doc/ directory. If you find something that needs fixing but cannot patch it yourself, please open an issue on GitHub.