Getting Started
Dynamoid is an Object-Document Mapper (ODM) for Amazon DynamoDB written in Ruby. It provides a familiar, ActiveRecord-like interface for Rails and standalone Ruby applications, bringing familiar ORM ergonomics to DynamoDB. Because DynamoDB fundamentally differs from relational databases, Dynamoid adapts the Active Record pattern around DynamoDB’s architectural realities and performance trade-offs, while providing an idiomatic Ruby interface for DynamoDB-specific features.
A primary goal of Dynamoid is to serve as a near drop-in replacement for ActiveRecord models in Rails applications. Because it adheres to ActiveModel conventions, Dynamoid works directly with standard Rails views, form builders, and controllers. This makes migrating an existing application or building new DynamoDB-backed services straightforward, without requiring a rewrite of your application layer.
The DynamoDB Data Model
DynamoDB stores data in tables, which contain items (analogous to rows or documents), and each item consists of attributes (analogous to columns or fields).
Unlike relational databases, DynamoDB tables do not enforce a column schema. The table definition specifies only the primary key, which uniquely identifies each item. All other attributes are dynamic—different items in the same table can carry different attributes, and an attribute only exists on an item when assigned a value.
A primary key can be either simple or composite. A simple primary key consists of a single partition key attribute (historically called a hash key), whose value must be unique across the entire table. A composite primary key combines a partition key with a sort key (historically called a range key); together they uniquely identify an item, so multiple items can share the same partition key value as long as their sort key values differ.
How you access data depends directly on these key attributes:
- A point lookup retrieves a single item directly by its primary key.
- A query operation retrieves items matching an exact partition key, optionally filtered by sort key conditions.
- A scan operation reads every item in the table when no partition key is specified.
Key Differences from Relational Databases
Because Dynamoid provides a familiar ActiveRecord-like interface, it is easy to assume that DynamoDB behaves like a relational database underneath. In practice, several architectural differences shape how you model and query your data.
Schemas, Primary Keys, and Writes
In PostgreSQL or MySQL, table schemas define every column and data type upfront. DynamoDB tables, by contrast, only declare their primary keys at the database level—non-key attributes are schemaless, so adding, renaming, or removing attributes does not require database migrations.
Primary keys also behave differently during writes:
- DynamoDB does not auto-generate primary keys or sequences; key values must always be provided on write.
- Primary keys are immutable once written; changing a key requires creating a new item and deleting the original.
- Updates and deletes must target an exact primary key—there is no equivalent to
UPDATE ... WHEREorDELETE ... WHERE.
Querying and Indexing
Relational databases provide an expressive query engine with automated index planning, dynamic sorting, random-access pagination, and server-side aggregation. DynamoDB trades this flexibility for predictable, single-digit millisecond latency at any scale, resulting in several fundamental constraints:
- Fast queries require an equality condition on the partition key, optionally refined with range conditions on the sort key.
- Filtering efficiently by other attributes requires defining a secondary index with those attributes as the index key.
- Results can only be sorted by the sort key—there is no arbitrary
ORDER BYon non-key attributes. - Result sets are traversed forward using cursors—there is no numeric
OFFSETto skip a given number of items. - There is no
GROUP BYor server-side aggregation (SUM,AVG,MIN,MAX); totals must be computed in application code. - Reads are eventually consistent by default and may briefly return stale data after a write unless you request a strongly consistent read.
Relationships and Joins
DynamoDB does not support database-level JOIN operations. Instead of normalizing data across tables and joining on foreign keys, relationships must be resolved through separate lookups or by denormalizing related data into a single item.
DynamoDB also does not enforce foreign key constraints at the storage level. Because the database does not verify that referenced items exist, deleting a target item without updating its references can leave dangling foreign keys, and there is no database-level cascading deletion or nullification (ON DELETE CASCADE or ON DELETE SET NULL). Referential integrity between related items must be coordinated by the application layer.
Transactions and Locking
In relational databases, you can open an interactive transaction block (BEGIN … COMMIT), acquire a pessimistic lock on rows with SELECT ... FOR UPDATE, run business logic in Ruby, and conditionally commit or roll back.
DynamoDB does not support interactive transactions or pessimistic locking. While it provides multi-item ACID transactions, they must execute as a single, all-or-nothing request—you cannot hold a transaction or row lock open while application code reads data and decides what to do next. Instead, concurrent updates are coordinated using conditional writes (which enable optimistic locking) or atomic update operations.
Operational Limits
DynamoDB also enforces several hard operational limits:
- An item cannot exceed 400 KB in total size (including attribute names and values).
- A single query or scan request returns at most 1 MB of data per page.
- Batch writes and deletes are capped at 25 items per request; batch reads and transactions are capped at 100 items.
The Active Record Pattern in Dynamoid
Dynamoid adapts the Active Record pattern, an architectural approach to database access originally cataloged by Martin Fowler in his patterns catalog and popularized in the Ruby community by Ruby on Rails.
In this pattern, an object encapsulates both database access and domain logic. Rather than separating domain models from a persistence layer (such as repositories or data mappers) or writing low-level database queries by hand, an Active Record model unites four core responsibilities:
- State — holds an individual item’s attributes in memory and exposes typed accessors.
- Persistence — saves changes and deletes items directly through instance methods (such as
user.saveanduser.destroy). - Querying — retrieves items through class-level finders such as
User.findandUser.where. - Domain logic — enforces validation rules and business methods directly on the model alongside its data.
Mapping Active Record to DynamoDB
In relational implementations of Active Record (such as ActiveRecord in Rails), models map classes to tables, rows to instances, and columns to object attributes. Dynamoid adapts these exact same principles to Amazon DynamoDB:
| Ruby / Dynamoid | DynamoDB Concept | Role |
|---|---|---|
Model class (User) | Table (users) | Maps to the table; coordinates queries and table-level configuration |
Model instance (user = User.new) | Item | Represents an individual item in memory and holds its attributes |
Field declaration (field :name) | Attribute | Defines typed getters, setters, type casting, and defaults |
Instance methods (user.save, user.destroy) | Item operations | Persists, updates, or deletes the individual item in DynamoDB |
Class methods (User.find, User.where) | Table read operations | Performs point lookups (GetItem), index queries (Query), or scans |
Instead of constructing low-level AWS SDK parameter hashes (such as client.put_item(item: { ... })), you interact with DynamoDB through expressive domain objects:
user = User.new(name: 'Alice', email: 'alice@example.com')
user.save
Declaring Models and Fields
Relational databases maintain a table schema that an ORM can inspect to define attribute accessors automatically. Because DynamoDB is schemaless, schema is defined at the application layer.
To declare a model, include Dynamoid::Document in a Ruby class and declare each attribute with field:
class User
include Dynamoid::Document
field :name
field :email
field :age, :integer
field :active, :boolean, default: true
end
Fields default to :string, so specifying the type for string attributes is optional. Declaring a field automatically generates reader, writer (name=), predicate (name?), raw reader (name_before_type_cast), and dirty-tracking methods:
user = User.new(name: 'Alice', active: true)
user.name # => "Alice"
user.name = 'Alicia'
user.active? # => true
If a DynamoDB item contains attributes not declared in your Ruby model, Dynamoid ignores them when loading the item into memory. When saving, Dynamoid only writes declared, modified attributes, leaving any undeclared attributes in DynamoDB intact.
Conventions and Defaults
Dynamoid follows convention over configuration, so a model only needs to declare its fields:
- Table names are derived from the pluralized class name (
User→users) and prefixed withconfig.namespace. - The primary key defaults to a string partition key named
id, populated with a random UUID on save if unset. - Models automatically include and maintain
created_atandupdated_atdatetime fields.
Note
To customize these defaults—such as specifying a custom table name, configuring a custom partition key name or type, or declaring a sort key for a composite primary key—refer to Table Mapping & Provisioning.
Basic CRUD Operations
Everyday persistence operations mirror ActiveRecord closely:
Creating
To instantiate a new model in memory and persist it to DynamoDB, call new and save:
user = User.new(name: 'Alice', email: 'alice@example.com')
user.age = 30
user.save
To instantiate and save a model in a single call, use create:
user = User.create(name: 'Bob', email: 'bob@example.com', age: 25)
Note
For advanced persistence patterns—such as bulk imports with
.import, atomic counters, conditional updates, and optimistic locking—refer to Persistence.
Reading and Querying
To look up an item directly by its primary key, use find:
user = User.find(user_id)
To query items by attribute conditions, use where:
active_users = User.where(active: true).all
adult = User.where('age.gte': 18).first
Note
For more query capabilities—including range conditions, attribute projection, consistent reads, and pagination—refer to Query Interface.
Updating
To modify attributes on a loaded model and persist the changes in one step, call update_attributes:
user.update_attributes(age: 31)
You can also assign attributes directly and call save:
user.age = 31
user.save
Deleting
To remove a loaded model instance and run its destroy callbacks, call destroy:
user.destroy
To delete an item directly by its primary key without instantiating the model or running callbacks, call delete:
User.delete(user_id)
Validations
You can declare validation rules on a model to verify its state before it is saved to DynamoDB:
class User
include Dynamoid::Document
field :name
validates :name, presence: true
end
user = User.new
user.valid? # => false
user.errors.full_messages # => ["Name can't be blank"]
user.save # => false
Lifecycle Callbacks
You can register callbacks to run logic before, around, or after events in a model’s lifecycle (such as save, create, update, and destroy):
class User
include Dynamoid::Document
field :email
before_save :normalize_email
private
def normalize_email
self.email = email.downcase if email.present?
end
end
Note
For the full list of lifecycle events, execution order, and how to halt operations from a callback, refer to Callbacks.
Table Creation
Unlike relational databases, DynamoDB is schemaless, so Dynamoid does not use database migration files. By default, new tables are automatically created when a model is saved for the first time, or can be pre-created in batch using a Rake task. To learn more, see Table Creation and Management.
Installation and Configuration
To add Dynamoid to your application, include the gem in your Gemfile and run bundle install:
gem 'dynamoid'
Next, set up your database connection depending on your environment.
Local Development
For local development and automated testing without an AWS account, start DynamoDB Local via Docker:
docker run --rm -d -p 8000:8000 amazon/dynamodb-local
Then create config/initializers/dynamoid.rb to connect to the local container with dummy credentials. Using Rails.env in config.namespace keeps development and test tables isolated:
Dynamoid.configure do |config|
config.namespace = "my_app_#{Rails.env}"
config.endpoint = 'http://localhost:8000'
config.region = 'us-east-1'
config.access_key = 'fake'
config.secret_key = 'fake'
end
Note
By default, DynamoDB Local runs purely in memory—all tables and data are discarded when the container stops. If you need data to persist between launches, you must explicitly configure DynamoDB Local to write to disk and configure a Docker volume to preserve those files on your host machine. For setup instructions, refer to Deploying DynamoDB Local with Docker.
AWS Environments
When connecting to Amazon DynamoDB, credentials and region are automatically discovered from standard environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION), AWS profiles, or IAM roles:
Dynamoid.configure do |config|
config.namespace = 'my_app'
end
The config.namespace option prefixes table names (e.g., my_app_users). Because DynamoDB table names are shared across an entire AWS account, this prefix prevents collisions between different environments (such as staging vs. test) or developers sharing a sandbox account.
Note
For advanced configuration options—including custom credentials, IAM role assumption, HTTP timeouts, and retry backoff strategies—refer to Configuration.
Rake Tasks
Dynamoid ships with Rake tasks for verifying connectivity and provisioning tables locally.
To test network connectivity and authentication with DynamoDB:
rake dynamoid:ping
To create tables (along with any declared secondary indexes) for all models in config.models_dir (app/models by default), skipping tables that already exist:
rake dynamoid:create_tables
In Rails applications, these tasks are loaded automatically. In standalone Ruby projects, define an :environment task that configures Dynamoid and require dynamoid/tasks in your Rakefile:
Rake::Task.define_task(:environment) do
require_relative 'config/boot'
end
require 'dynamoid/tasks'
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.
Table Mapping & Provisioning
In Dynamoid, every model maps to an Amazon DynamoDB table. While Dynamoid provides sensible conventions for table names and primary keys out of the box, you can customize table identity, primary keys, secondary indexes, and provisioning settings on the model class.
Table Naming
By default, Dynamoid derives the DynamoDB table name by pluralizing the model class name and prepending the configured namespace:
class User
include Dynamoid::Document
end
User.table_name # => "<namespace>_users"
Namespaces
To prevent name collisions between environments (such as development, staging, and production) or between different applications sharing an AWS account, configure a global namespace prefix:
Dynamoid.configure do |config|
config.namespace = 'myapp_production'
end
User.table_name # => "myapp_production_users"
When config.namespace is not set, Dynamoid defaults to dynamoid in standalone Ruby applications (mapping User to dynamoid_users) and dynamoid_<app_name>_<env> in Rails applications (mapping User to dynamoid_myapp_development_users).
Tip
For multi-account architectures, dedicated versus shared account strategies, and developer sandbox isolation, see Table Namespaces in the Configuration guide.
Custom Table Names
To override the inferred table name for a specific model, pass the :name option:
class User
include Dynamoid::Document
table name: :legacy_users_table
end
When a custom name is specified, Dynamoid still prefixes it with the configured namespace unless accessed via an ARN.
Important
All table configuration options must be specified in a single
tablecall. Callingtablemultiple times silently discards previously configured settings.
Cross-Account and Shared Tables (ARN)
To connect to a DynamoDB table in another AWS account or region, or to reference an externally managed table without applying a namespace prefix, specify its Amazon Resource Name (ARN) via :arn:
class AuditLog
include Dynamoid::Document
table arn: 'arn:aws:dynamodb:us-east-1:123456789012:table/corporate_audit_logs'
end
DynamoDB table ARNs uniquely identify tables across AWS accounts and follow the format arn:aws:dynamodb:<region>:<account-id>:table/<table-name>.
Primary Key
In DynamoDB, a primary key uniquely identifies each item in a table. It can be a simple primary key consisting solely of a partition key, or a composite primary key combining a partition key with a sort key.
Partition Key
DynamoDB requires every table to declare a partition key (historically called a hash key). The partition key value determines the physical partition where DynamoDB stores the item, and it must be unique across all items in a table with a simple primary key.
By convention, Dynamoid expects the table’s partition key to be named id with type :string, and automatically declares an id field on the model. For string partition keys, Dynamoid automatically generates a UUID string on save if no value has been assigned. When using a numeric partition key, you must provide a value explicitly before saving.
To customize the partition key name and its data type, pass :key and :key_type to table (no separate field declaration is needed):
class User
include Dynamoid::Document
table key: :user_id, key_type: :integer
end
Sort Key
A composite primary key combines a partition key with a sort key (historically called a range key). In a composite key table, multiple items can share the same partition key value as long as their sort key values differ.
To declare a sort key, use the range class method:
class Order
include Dynamoid::Document
range :placed_at, :datetime
field :total, :number
end
The second argument to range specifies the sort key’s data type, which defaults to :string if omitted.
Note
Dynamoid associations (
belongs_to,has_many,has_one, andhas_and_belongs_to_many) currently require simple primary keys. If your model uses a composite primary key, manage relationships through explicit queries instead of association macros.
Supported Key Types
DynamoDB requires primary key attributes (both partition and sort keys) to be of a scalar type—complex types such as sets, arrays, and maps cannot serve as keys. Dynamoid supports :string (default), :integer, :number, :datetime, and :date (as well as :serialized and custom types).
For full details on type casting and custom types, see Fields & Data Types.
Custom Partition Key Field
If you need to declare the partition key with the field method—such as to configure a non-default type or pass field options like store_as_string: true—suppress the automatic id field generation using skip_generating_fields: [:id] to avoid warnings about overriding existing accessor methods:
class AuditLog
include Dynamoid::Document
table skip_generating_fields: [:id]
field :id, :date, store_as_string: true
end
Secondary Indexes
By default, DynamoDB only supports fast, direct lookups by a table’s primary key—filtering by any other attribute requires scanning the entire table. To avoid full-table scans, DynamoDB provides secondary indexes (Global Secondary Indexes and Local Secondary Indexes), which establish alternate keys over a subset of item attributes and are updated automatically as items change.
Declaring secondary indexes on a Dynamoid model is optional. Dynamoid uses index declarations to:
- Automatically select and query a matching index instead of scanning the table, or target a declared index explicitly (see Query Interface).
- Provision the declared indexes in DynamoDB when Dynamoid creates the table (see Table Creation and Management).
If a table is provisioned externally and your application does not benefit from querying a given index through Dynamoid, you do not need to declare it on the model.
Important
Dynamoid only provisions secondary indexes when creating a new table; it does not add, modify, or remove indexes on an existing table in DynamoDB.
Global Secondary Indexes
A Global Secondary Index defines its own partition key and optional sort key, both of which can differ from the table’s primary key. To declare one, call global_secondary_index with :hash_key and an optional :range_key:
class Order
include Dynamoid::Document
field :number
field :customer_id
field :placed_at, :datetime
global_secondary_index hash_key: :number
global_secondary_index hash_key: :customer_id, range_key: :placed_at
end
Declare the index after the table settings and the fields it references, as Dynamoid resolves the table name and key fields when the index is defined. Like primary keys, index keys must be of a scalar type (see Supported Key Types).
Local Secondary Indexes
A Local Secondary Index shares the table’s partition key and defines an alternate sort key. To declare one, call local_secondary_index with :range_key:
class Order
include Dynamoid::Document
range :placed_at, :datetime
field :total, :number
local_secondary_index range_key: :total
end
Declare the index after the table settings, primary sort key, and the field it references. The index sort key must be of a scalar type and differ from the table’s primary sort key.
Projected Attributes
In addition to the table’s primary key and the index’s own keys, a secondary index can store other attributes copied from the item, known as projected attributes. Both global_secondary_index and local_secondary_index accept :projected_attributes, which defaults to :keys_only (projecting only the table and index keys). You can pass :all to copy every attribute from the item, or an array of non-key attribute names (such as [:total, :status]) to copy specific attributes:
class Order
include Dynamoid::Document
field :customer_id
field :placed_at, :datetime
global_secondary_index hash_key: :customer_id,
range_key: :placed_at,
projected_attributes: :all
end
Note
Which attributes you project affects how Dynamoid queries the index. In particular, Dynamoid only selects a Global Secondary Index automatically during queries when
projected_attributes: :allis declared on the index (see Query Interface).
Index Naming
By default, Dynamoid generates an index name from the table name and the index key names in the format <table_name>_index_<hash_key> or <table_name>_index_<hash_key>_<range_key> (for example, <table_name>_index_customer_id_placed_at).
To provide your own index name on either index type, pass the :name option:
class Order
include Dynamoid::Document
field :number
global_secondary_index hash_key: :number, name: 'orders_by_number'
end
Dynamoid uses the provided :name as-is without adding a table or namespace prefix. Setting an explicit :name is required when an externally provisioned table uses index names that do not follow Dynamoid’s convention, and is also useful for giving an index a shorter name to reference in queries.
Table Creation and Management
Dynamoid provides utilities to define basic table properties in model classes and create or delete tables programmatically. However, these tools are intended primarily for local development and test suites. Because Dynamoid focuses on application-level data modeling rather than full infrastructure management, it does not alter existing tables or provide schema migrations. In production environments, DynamoDB tables are typically provisioned and maintained using Infrastructure as Code (such as Terraform, AWS CDK, or CloudFormation).
Implicit Creation
By default, Dynamoid automatically creates the underlying DynamoDB table the first time a model is saved if the table does not yet exist. This behavior is controlled by the create_table_on_save configuration option, which defaults to true.
In local development and automated test suites, automatic creation eliminates manual table setup. In production, however, table creation on save is undesirable: Dynamoid configures only basic table properties, and blocking on table creation in AWS introduces multi-second latency to user requests.
To disable auto-creation in production:
Dynamoid.configure do |config|
config.create_table_on_save = false
end
Explicit Creation and Deletion
To create or delete a model’s table programmatically, call create_table or delete_table:
User.create_table
User.delete_table
Both methods are asynchronous by default and return immediately without waiting for DynamoDB to finish provisioning or deleting the table. To poll DynamoDB and wait until the operation completes, pass sync: true:
User.create_table(sync: true)
User.delete_table(sync: true)
When creating tables, Dynamoid provisions the primary key attributes along with any Global or Local Secondary Indexes declared on the model (see Secondary Indexes).
To create tables for all declared models at once, run the provided Rake task (see Rake Tasks):
rake dynamoid:create_tables
Note
When a model declares Global or Local Secondary Indexes, Dynamoid automatically creates the table synchronously. DynamoDB allows creating only one table with secondary indexes at a time, so Dynamoid waits for the table and its indexes to become available before returning.
Table Settings
When Dynamoid creates a new table (whether automatically or explicitly), it applies the provisioning and schema settings declared on the model class.
Important
Dynamoid does not alter existing tables in DynamoDB.
Capacity and Billing Modes
DynamoDB supports two billing modes: Provisioned and On-Demand. You can configure this per model using the table method.
In on-demand mode, AWS dynamically scales throughput to match workload traffic without upfront capacity planning:
class Session
include Dynamoid::Document
table capacity_mode: :on_demand
end
In provisioned mode, specify dedicated Read Capacity Units (RCUs) and Write Capacity Units (WCUs):
class User
include Dynamoid::Document
table capacity_mode: :provisioned, read_capacity: 500, write_capacity: 200
end
If omitted on the model, the capacity mode and capacity units fall back to the capacity_mode, read_capacity, and write_capacity global configuration options. When the capacity mode is :on_demand, capacity settings are ignored during table creation.
Time To Live (TTL)
Dynamoid integrates with DynamoDB’s native Time To Live (TTL) mechanism to automatically delete expired items. To configure it, pass the expires option to table and declare a corresponding numeric field (:integer or :number):
class Session
include Dynamoid::Document
table expires: { field: :ttl, after: 86_400 } # 24 hours in seconds
field :ttl, :integer
end
When saving a model, Dynamoid sets the TTL attribute to the current Unix timestamp plus :after seconds whenever the attribute value is nil. When creating the table, Dynamoid also enables TTL on the backing DynamoDB table for the specified attribute (if the table is provisioned externally, such as via Terraform or CloudFormation, you must enable TTL in your infrastructure configuration).
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.
Fields & Data Types
DynamoDB tables are schemaless beyond their primary keys: items can contain arbitrary attributes, and an attribute only exists when assigned a value. Dynamoid brings structure to this model by letting you declare an explicit attribute schema directly on your Ruby models.
Attributes on a Dynamoid model must be declared using field (or range for sort keys). Undeclared attributes stored in DynamoDB are safely ignored when loading items, preventing unexpected database fields from polluting in-memory models:
class User
include Dynamoid::Document
field :name
field :email
field :age, :integer
end
Field declarations do far more than define standard Ruby getter and setter methods. They establish an application-level schema that manages the translation between Ruby models and DynamoDB:
- Type casting — casts assigned values into declared Ruby types (such as strings, integers, dates, arrays, or hashes).
- Non-native types — serializes types DynamoDB lacks natively (dates, timestamps, and custom types).
- Time zone awareness — normalizes timestamps to a uniform storage time zone (UTC by default) and presents them in the application’s time zone.
- Typed collections — enforces and casts element types inside sets and arrays.
- Constraint handling — handles DynamoDB limitations like prohibited empty sets.
Declaring Fields & Attribute Access
You define attributes and sort keys using class-level macros, which automatically generate idiomatic Ruby reader, writer, and query accessors on model instances.
Declaring Fields
Declare attributes on your model by calling the field class method. It accepts the attribute name as a symbol (or string), an optional data type, and configuration settings:
class User
include Dynamoid::Document
field :email
field :age, :integer
field :active, :boolean, default: true
end
When the data type argument is omitted, Dynamoid defaults to :string.
Declaring Sort Key
To declare a sort key for a composite primary key, use the range class method instead of field:
class Order
include Dynamoid::Document
range :placed_at, :datetime
end
The range method declares a field with the exact same data types and options as field, while registering that attribute as the table’s composite sort key (see Table Mapping & Provisioning).
Generated Accessors
For every declared field, Dynamoid generates three instance methods on your model:
- Reader (
<attribute>) — returns the type-casted attribute value. - Writer (
<attribute>=) — type casts the incoming value and updates in-memory storage. - Predicate query (
<attribute>?) — returnstrueif the attribute has a value other thanfalseornil.
user = User.new
user.email # => nil
user.email? # => false
user.email = 'ada@example.com'
user.email # => "ada@example.com"
user.email? # => true
If a declared field name conflicts with an existing Ruby method on the class, Dynamoid logs a warning during class definition to alert you of the method redefinition.
Direct Attribute Access
In addition to generated reader and writer methods, you can read attributes directly by name using read_attribute or its hash-style alias []:
user.read_attribute(:age) # => 35
user[:age] # => 35
To write an attribute directly by name, use write_attribute or []=:
user.write_attribute(:age, 36)
user[:age] = 36
To retrieve all type-casted attributes currently loaded on the instance, call attributes:
user.attributes
# => { id: "a8f5c3...", email: "ada@example.com", age: 36, active: true, ... }
You can also read all unconverted values assigned before type casting by calling attributes_before_type_cast, or inspect a single attribute’s raw input with read_attribute_before_type_cast(:age).
General Field Options
The field macro accepts configuration options to customize attribute behavior. While type-specific options (such as :of and :store_as_string) are detailed in Data Types, general options such as :default and :alias can be applied to any field declaration.
Default Values
Fields can declare default values that are applied when no value is passed during initialization. Defaults can be static values or dynamic callables:
class User
include Dynamoid::Document
field :status, :string, default: 'active'
field :confirmation_token, :string, default: -> { SecureRandom.hex(16) }
end
When a default is specified as a callable object (such as a lambda or proc responding to #call), Dynamoid evaluates the block anew for each initialized model instance. For static values, mutable objects (such as strings or arrays) are duplicated upon initialization so separate instances do not share state.
Attribute Aliasing
Legacy DynamoDB tables or external systems often use camelCase or uppercase attribute names (such as firstName or ORDER_STATUS). You can define an idiomatic Ruby snake_case alias using the :alias option:
class User
include Dynamoid::Document
field :firstName, :string, alias: :first_name
end
When an alias is specified, Dynamoid generates reader, writer, predicate query, and raw reader methods for both names:
user = User.new(firstName: 'Ada')
user.first_name # => "Ada"
user = User.new(first_name: 'Ada')
user.firstName # => "Ada"
user.first_name = 'Grace'
user.firstName # => "Grace"
In the underlying DynamoDB item, the attribute is stored under the primary declared name (firstName).
Data Types
Dynamoid maps declared fields to native DynamoDB data types (scalar, document, and set types), while providing type casting for standard Ruby classes, collections, and custom types.
| Dynamoid Type | Ruby Class | DynamoDB Type | Description |
|---|---|---|---|
:string | String | String | UTF-8 text string. |
:integer | Integer | Number | Whole number; truncates fractions. |
:number | BigDecimal | Number | Arbitrary-precision decimal. |
:boolean | TrueClass / FalseClass | Boolean (default) or String | Boolean value (true or false). |
:binary | String | String (default, Base64) or Binary | Raw binary data. |
:datetime | DateTime | Number (default) or String | Timestamp with sub-second precision. |
:date | Date | Number (default) or String | Calendar date without time or time zone. |
:set | Set | String, Number, or Binary Set | Homogeneous collection of unique scalar values. |
:array | Array | List | Ordered collection of heterogeneous elements. |
:map | Hash | Map | Key-value dictionary. |
:raw | Any supported Ruby class (Hash, Array, etc.) | Any native DynamoDB type | Preserves values and nested structures without type casting. |
:serialized | Any serializable object | String | Serializes arbitrary objects (YAML by default). |
| Custom Type | User-defined class | Any native DynamoDB type | Domain object with custom dump and load methods. |
Scalar Types
Scalar types represent single primitive values mapped to DynamoDB’s native scalar storage formats.
Strings
On assignment, Dynamoid casts values into a String via #to_s (booleans become 't' or 'f'). String objects are duplicated on assignment, so mutating the original string does not affect the model attribute. In-memory attributes always return a String (or nil if unset).
In DynamoDB, strings are persisted as native String attributes, which store Unicode text encoded in UTF-8. Strings assigned in other encodings (such as ISO-8859-1) are transcoded to UTF-8 on save, and reading from DynamoDB returns a UTF-8 string. If a string contains arbitrary binary data that cannot be encoded as UTF-8, saving raises a JSON::GeneratorError; use Binary instead.
By default, assigning an empty string ("") causes Dynamoid to persist the attribute as nil. To preserve empty strings in DynamoDB, set config.store_empty_string_as_nil = false.
Integers
On assignment, Dynamoid casts values into an Integer by calling #to_i on any object that responds to it, while booleans map explicitly to 1 (true) or 0 (false). For example, floats are truncated towards zero, numeric strings like "1abc" become 1, and non-numeric strings like "abc" become 0.
Blank strings ("" or " "), non-finite floats (Float::NAN, Float::INFINITY), and objects that do not respond to #to_i cast to nil.
In DynamoDB, integers are stored as native Number attributes. When loaded from DynamoDB, attributes are returned as Integer (or nil if unset).
Numbers
The :number type manages arbitrary-precision decimals, currencies, ratings, and floating-point data.
On assignment, Dynamoid casts numeric inputs (including floats, integers, symbols, and numeric strings) into BigDecimal via #to_d to prevent IEEE 754 floating-point rounding errors. Booleans cast to 1 (true) or 0 (false), while blank strings, non-finite floats, and objects without #to_d cast to nil.
In DynamoDB, numbers are stored as native Number attributes. When loaded from DynamoDB, attributes are returned as BigDecimal (or nil if unset).
Booleans
On assignment, Dynamoid casts inputs into true or false. Values recognized as false include false, 'false', 'FALSE', 0, '0', 'f', 'F', 'off', and 'OFF'. Empty strings cast to nil. All other values cast to true. In-memory attributes always return true, false, or nil.
In DynamoDB, boolean fields are stored by default as native Boolean attributes:
class User
include Dynamoid::Document
field :active, :boolean
end
user = User.create!(active: true)
# DynamoDB item attribute:
# "active": true (Boolean)
To store booleans using legacy single-character strings ('t' or 'f') for compatibility with older tables, set store_as_native_boolean: false on the field, or set config.store_boolean_as_native = false globally:
class User
include Dynamoid::Document
field :active, :boolean, store_as_native_boolean: false
end
user = User.create!(active: true)
# DynamoDB item attribute:
# "active": "t" (String)
Binary
The :binary type stores arbitrary binary data, such as images, compressed payloads, or encrypted buffers.
By default, binary fields are stored in DynamoDB as Base64-encoded String attributes, and accept binary strings:
class User
include Dynamoid::Document
field :avatar, :binary
end
user = User.create!(avatar: "\x00\x88\xFF".b)
# DynamoDB item attribute:
# "avatar": "AIj/" (String, Base64-encoded)
To store raw binary data natively as DynamoDB Binary attributes, pass store_as_native_binary: true on the field, or set config.store_binary_as_native = true globally. Native binary fields accept String, StringIO, or IO objects (such as an open File) directly:
class User
include Dynamoid::Document
field :avatar, :binary, store_as_native_binary: true
end
File.open('avatar.png', 'rb') do |file|
user = User.create!(avatar: file)
end
# DynamoDB item attribute:
# "avatar": <raw bytes> (Binary)
When loaded from DynamoDB, binary attributes are always returned as String instances with ASCII-8BIT (binary) encoding in either storage mode. Objects that are neither strings nor IO objects assigned to binary fields are converted via #to_s.
DateTimes
The :datetime type manages timestamps with sub-second precision.
On assignment, Dynamoid casts values (including Time, DateTime, Date, and formatted strings) into DateTime via #to_datetime. When parsing date strings without an explicit time zone offset, Dynamoid assumes the offset configured by config.application_timezone. When loaded from DynamoDB, attributes are returned as DateTime adjusted to config.application_timezone (see Time Zones).
In DynamoDB, datetime fields are stored by default as numeric timestamps (seconds and nanoseconds since the Unix epoch) in Number attributes:
class Order
include Dynamoid::Document
field :placed_at, :datetime
end
order = Order.create!(placed_at: '2026-10-11 12:00:00')
# DynamoDB item attribute:
# "placed_at": 1791720000.0 (Number, seconds since Unix epoch)
To store timestamps as human-readable ISO-8601 strings, pass store_as_string: true on the field, or set config.store_datetime_as_string = true globally. When stored as strings, timestamps are normalized to config.dynamodb_timezone (see Time Zones):
class Order
include Dynamoid::Document
field :placed_at, :datetime, store_as_string: true
end
order = Order.create!(placed_at: '2026-10-11 12:00:00')
# DynamoDB item attribute:
# "placed_at": "2026-10-11T12:00:00+00:00" (String, ISO-8601)
Note
Storing timestamps as numbers preserves nanosecond precision and allows exact numerical range queries. Storing timestamps as ISO-8601 strings provides human-readable values in external tools and the AWS Console, but string timestamps truncate fractional seconds.
Dates
The :date type manages calendar dates without time or time zone components.
On assignment, Dynamoid casts values (including Date, DateTime, Time, and formatted strings like "2026-10-11") into Date via #to_date. In-memory attributes always return a Date (or nil if unset).
In DynamoDB, dates are stored by default as an integer count of days since the Unix epoch (January 1, 1970) in Number attributes:
class User
include Dynamoid::Document
field :birth_date, :date
end
user = User.create!(birth_date: '1990-05-15')
# DynamoDB item attribute:
# "birth_date": 7439 (Number, integer days since January 1, 1970)
To store dates as formatted ISO-8601 strings ("YYYY-MM-DD"), set store_as_string: true on the field, or set config.store_date_as_string = true globally:
class User
include Dynamoid::Document
field :birth_date, :date, store_as_string: true
end
user = User.create!(birth_date: '1990-05-15')
# DynamoDB item attribute:
# "birth_date": "1990-05-15" (String, ISO-8601)
Collection Types
Collection types store unique scalar sets, ordered lists, and key-value maps using native DynamoDB set and document structures.
Sets
Sets store collections of unique scalar values.
On assignment, Dynamoid casts objects responding to #to_set (such as arrays) into a Set. When the :of option is omitted, elements are kept as-is:
class User
include Dynamoid::Document
field :tags, :set
end
user = User.create!(tags: %w[ruby aws ruby])
user.tags # => #<Set: {"ruby", "aws"}>
# DynamoDB item attribute:
# "tags": ["ruby", "aws"] (String Set)
To enforce and cast element types, specify the :of option. Supported element types include :string, :integer, :number, :date, :datetime, :serialized, and custom types. Each element is cast to the declared type:
class User
include Dynamoid::Document
field :roles, :set, of: :string
end
user = User.create!(roles: [:admin, 'editor', 'admin'])
user.roles # => #<Set: {"admin", "editor"}>
# DynamoDB item attribute:
# "roles": ["admin", "editor"] (String Set)
Element type options can also be provided using a nested Hash, where standard field type options can be specified:
field :payloads, :set, of: { serialized: { serializer: JSON } }
When nested options are omitted, element type casting and storage respect global configuration options (such as config.store_date_as_string or config.store_datetime_as_string).
In DynamoDB, sets are stored as native String Set, Number Set, or Binary Set attributes. Sets carry strict database-level constraints: all elements must share the same scalar type, duplicates are ignored, and empty sets are strictly prohibited by DynamoDB. To prevent database validation errors, Dynamoid persists empty sets (Set.new or []) as nil.
Arrays
Arrays store ordered collections of elements persisted as native DynamoDB List attributes.
On assignment, Dynamoid casts objects responding to #to_a into an Array (objects not responding to #to_a cast to nil). When the :of option is omitted, elements are kept as-is:
class User
include Dynamoid::Document
field :preferences, :array
end
user = User.create!(preferences: %w[email sms])
user.preferences # => ["email", "sms"]
# DynamoDB item attribute:
# "preferences": ["email", "sms"] (List)
To enforce and cast element types, specify the :of option. Supported element types include :string, :integer, :number, :date, :datetime, :serialized, and custom types. Each element is cast to the declared type:
class User
include Dynamoid::Document
field :scores, :array, of: :integer
end
user = User.create!(scores: ['10', 20.5, 30])
user.scores # => [10, 20, 30]
# DynamoDB item attribute:
# "scores": [10, 20, 30] (List of Numbers)
Element type options can also be provided using a nested Hash, where standard field type options can be specified:
field :login_times, :array, of: { datetime: { store_as_string: true } }
When nested options are omitted, element type casting and storage respect global configuration options.
Untyped arrays also support non-scalar element types (such as nested hashes or arrays):
user = User.create!(
preferences: [
{ channel: 'email', frequency: 'daily' },
{ channel: 'sms', frequency: 'weekly' }
]
)
# DynamoDB item attribute:
# "preferences": [{"channel": "email", "frequency": "daily"}, {"channel": "sms", "frequency": "weekly"}] (List of Maps)
user.reload.preferences
# => [{ "channel" => "email", "frequency" => "daily" }, { "channel" => "sms", "frequency" => "weekly" }]
In DynamoDB, arrays are stored as native List attributes. Unlike Sets, DynamoDB Lists preserve insertion order, allow duplicate elements, and natively support empty lists ([]).
Maps
Maps store key-value dictionaries persisted as native DynamoDB Map attributes.
On assignment, Dynamoid casts objects responding to #to_hash or #to_h into a Hash. In-memory attributes return a Hash (or nil if unset):
class User
include Dynamoid::Document
field :settings, :map
end
user = User.create!(settings: { theme: 'dark', language: 'en' })
# DynamoDB item attribute:
# "settings": {"theme": "dark", "language": "en"} (Map)
user.reload.settings
# => { theme: "dark", language: "en" }
Maps also support nested non-scalar values (such as nested hashes or arrays):
user = User.create!(
settings: {
notifications: { email: true, sms: false }
}
)
# DynamoDB item attribute:
# "settings": {"notifications": {"email": true, "sms": false}} (Map)
user.reload.settings
# => { notifications: { email: true, sms: false } }
In DynamoDB, maps are persisted as native Map attributes with stringified keys. When items are loaded from DynamoDB, all map keys are symbolized recursively. Numbers inside maps reload as BigDecimal by default; set config.convert_big_decimal = true to convert them to Float values upon reload.
Untyped Fields (:raw)
The :raw type stores arbitrary Ruby data structures directly without type casting. On assignment, Dynamoid performs no conversion, preserving the assigned object in memory as-is:
class User
include Dynamoid::Document
field :metadata, :raw
end
user = User.create!(metadata: { client: 'mobile', config: { retries: 3 }, tags: ['beta', 42] })
# DynamoDB item attribute:
# "metadata": {"client": "mobile", "config": {"retries": 3}, "tags": ["beta", 42]} (Map)
user.reload.metadata
# => { client: "mobile", config: { retries: 3 }, tags: ["beta", 42] }
In DynamoDB, :raw fields are stored directly as native DynamoDB types: hashes are stored as Maps, arrays as Lists, numbers (Integer, Float, BigDecimal) as Numbers, and IO objects (IO, StringIO) as Binary attributes, alongside strings, booleans, and sets.
When items are reloaded from DynamoDB, keys in nested hashes are symbolized automatically (matching :map behavior). Numbers inside nested hashes reload as BigDecimal by default and can be converted to Float via config.convert_big_decimal = true.
Object Serialization (:serialized)
The :serialized type encodes arbitrary Ruby objects into a single DynamoDB String attribute using a text-based coder.
Unlike :map or :raw (which decompose Ruby structures into native DynamoDB Map and List attributes), :serialized packs the entire object into an encoded text string. This allows you to store Ruby objects that DynamoDB does not support natively (such as a Range, Structs, or complex object graphs), as well as empty collections (such as empty sets) without triggering DynamoDB collection constraints:
class User
include Dynamoid::Document
field :session_data, :serialized
end
user = User.create!(session_data: { user_id: 123, role: 'admin' })
# DynamoDB item attribute:
# "session_data": "---\n:user_id: 123\n:role: admin\n" (String)
user.reload.session_data
# => { user_id: 123, role: "admin" }
By default, objects are encoded using YAML. You can specify an alternative serializer (such as JSON or any object implementing .dump and .load) via the :serializer option:
class User
include Dynamoid::Document
field :session_data, :serialized, serializer: JSON
end
user = User.create!(session_data: { user_id: 123, role: 'admin' })
# DynamoDB item attribute:
# "session_data": "{\"user_id\":123,\"role\":\"admin\"}" (String)
user.reload.session_data
# => { "user_id" => 123, "role" => "admin" }
On assignment, Dynamoid performs no type casting, preserving the original Ruby object in memory. Assigning nil stores nil (which is omitted from DynamoDB by default).
In DynamoDB, serialized fields are persisted as native String attributes. Dynamoid deserializes YAML safely using YAML.safe_load with permitted classes governed by config.yaml_permitted_classes; set config.use_yaml_unsafe_load = true to enable unsafe loading for legacy compatibility (see YAML Deserialization).
Custom Types
Custom types allow you to use dedicated Ruby classes as field types, mapping domain objects—such as Value Objects or standard library classes (IPAddr, URI)—directly to DynamoDB attributes.
Unlike scalar fields (which store disconnected primitives) or :serialized (which stores opaque text blobs), custom types may encapsulate business logic, validations, and calculations inside rich Ruby objects while persisting them as native DynamoDB types (such as strings, numbers, maps, or lists).
To declare a custom type, pass the Ruby class directly to field instead of a type name:
class Order
include Dynamoid::Document
field :total, Money
end
Custom types can also be used in typed arrays and sets with the :of option:
field :price_tiers, :array, of: Money
On assignment, Dynamoid performs no type casting, preserving the assigned Ruby object in memory as-is.
When persisting to DynamoDB, Dynamoid serializes the object by calling dynamoid_dump (either on the instance or on the field class), which must return a supported primitive Ruby type (such as a String, Numeric, Hash, or Array). When loading from DynamoDB, Dynamoid reconstructs the object by calling .dynamoid_load on the declared field class.
Custom types can optionally define a class method .dynamoid_field_type returning a Dynamoid field type (such as :integer, :number, :datetime, or :date). When this method is not implemented, Dynamoid defaults to :string. Dynamoid uses this when creating tables to define a table schema with the corresponding DynamoDB type whenever the field serves as a partition or sort key of a table or its index.
In practice, custom types are usually implemented using one of two patterns: as a self-serializing Value Object, or via a standalone adapter class.
Value Objects
A Value Object is an object whose equality is based on its value rather than its object identity. Value Objects may encapsulate validation, calculations, and formatting rules directly within their class definition.
When you control the class source code, make the class self-serializing by implementing #dynamoid_dump on the instance and .dynamoid_load on the class:
class Money
attr_reader :cents, :currency
def initialize(cents, currency = 'USD')
@cents = cents.to_i
@currency = currency.to_s
end
def dynamoid_dump
"#{cents} #{currency}"
end
def self.dynamoid_load(string)
cents, currency = string.to_s.split
new(cents, currency)
end
def ==(other)
other.is_a?(Money) && cents == other.cents && currency == other.currency
end
alias eql? ==
def hash
[cents, currency].hash
end
end
Declare the field on your model and interact with it as a standard Ruby object:
class Order
include Dynamoid::Document
field :total, Money
end
order = Order.create!(total: Money.new(4999, 'USD'))
# DynamoDB item attribute:
# "total": "4999 USD" (String)
reloaded_order = Order.find(order.id)
reloaded_order.total
# => #<Money:0x... @cents=4999, @currency="USD">
reloaded_order.total.cents # => 4999
reloaded_order.total.currency # => "USD"
Adapters
When using classes from the Ruby standard library (IPAddr, URI) or third-party gems that you cannot or prefer not to modify directly, define a standalone Adapter class.
An adapter implements both .dynamoid_dump(object) and .dynamoid_load(serialized_value) as class methods:
require 'ipaddr'
class IPAddrAdapter
def self.dynamoid_dump(ip)
ip&.to_s
end
def self.dynamoid_load(string)
IPAddr.new(string) if string.present?
end
end
Declare the attribute using the adapter class. Your application interacts directly with instances of the adapted class (IPAddr), while Dynamoid delegates persistence and reconstruction to the adapter behind the scenes:
class RequestLog
include Dynamoid::Document
field :remote_ip, IPAddrAdapter
end
log = RequestLog.create!(remote_ip: IPAddr.new('192.168.1.1'))
# DynamoDB item attribute:
# "remote_ip": "192.168.1.1" (String)
reloaded_log = RequestLog.find(log.id)
reloaded_log.remote_ip
# => #<IPAddr: IPv4:192.168.1.1/...>
reloaded_log.remote_ip.ipv4? # => true
Change Detection
Dynamoid tracks changes in custom type attributes to determine which fields to update when saving. This includes detecting in-place mutations, where an object’s internal state changes without reassigning the attribute (for example, calling a mutating method on a custom object rather than assigning a new instance).
To detect these changes, Dynamoid supports two comparison strategies:
- Serialized comparison (default) — serializes the attribute value and compares the result against the database state.
- In-memory comparison — compares the Ruby objects directly in memory using
#==.
Serialized comparison works out of the box without requiring #==, but serializing values whenever checking for changes (such as calling changed? or saving) incurs extra overhead. To enable in-memory comparison instead, pass comparable: true in the field declaration:
class Order
include Dynamoid::Document
field :total, Money, comparable: true
end
Important
Only enable
comparable: trueif the custom type implements#==for value equality. If the class relies on Ruby’s defaultObject#==(which checks object identity), two instances with the same state will never evaluate as equal. As a result, the attribute will always appear changed, triggering unnecessary DynamoDB writes on every save.
Type Casting
Dynamoid type casts attribute values into their declared types upon assignment while retaining uncast input for validations and form re-rendering.
Type casting runs immediately when an attribute is assigned, not when the model is saved:
class User
include Dynamoid::Document
field :age, :integer
field :active, :boolean
end
user = User.new
user.age = '35'
user.age # => 35
user.active = 'false'
user.active # => false
Because type casting runs on assignment, in-memory model instances always hold typed values.
When validation fails or when re-rendering user input in web forms, you often need the original input string before type casting altered it. ActiveModel validations (such as validates_numericality_of) also inspect the raw value to detect non-numeric input rather than evaluating coerced fallbacks like 0.
Dynamoid preserves this uncast input:
user = User.new(age: 'invalid_number')
user.age # => 0
user.age_before_type_cast # => "invalid_number"
user.read_attribute_before_type_cast(:age) # => "invalid_number"
user.attributes_before_type_cast
# => { age: "invalid_number" }
Implicit Fields
When Dynamoid::Document is included in a model class, it implicitly declares three standard attributes:
id(:string) — default partition key attribute.created_at(:datetime) — timestamp set automatically when the item is first persisted.updated_at(:datetime) — timestamp refreshed automatically whenever the item is saved.
Partition Key (id)
Every DynamoDB table requires a partition key. By default, Dynamoid implicitly declares an id field with type :string and generates a random UUID string on save if no explicit id value is provided:
user = User.new
user.id # => nil
user.save!
user.id # => "a8f5c310-8e12-4d2b-9e45-..."
To customize the partition key attribute name or type, see Partition Key in the Table Mapping & Provisioning guide.
Timestamps
Dynamoid maintains created_at and updated_at timestamps on every model instance. When an item is first saved, Dynamoid sets both fields to the current time (unless a value was already assigned). On subsequent updates, updated_at is refreshed automatically.
To disable timestamps globally across your application, configure the setting in an initializer:
Dynamoid.configure do |config|
config.timestamps = false
end
To disable timestamps for a specific model while leaving them active for the rest of the application, pass timestamps: false to table:
class AuditLog
include Dynamoid::Document
table timestamps: false
end
When timestamps are disabled, Dynamoid does not declare created_at or updated_at fields on the model and performs no automatic timestamp tracking.
Overriding Defaults
When you need to customize an implicit field (such as changing its type or options), redeclaring the field directly triggers a logger warning about method redefinition.
To suppress the default field declaration cleanly, pass the field names (:id, :created_at, or :updated_at) to skip_generating_fields in table. Unlike timestamps: false (which disables timestamp tracking entirely), skip_generating_fields only suppresses the default field declaration so you can redeclare it with custom options, while Dynamoid continues to manage the timestamp automatically on save:
class Order
include Dynamoid::Document
table skip_generating_fields: [:created_at]
field :created_at, :datetime, store_as_string: true
end
This option is also used when redeclaring the partition key with a non-default type or custom field options (see Custom Partition Key Field).
Storage and Serialization
Dynamoid provides options to configure how attributes are serialized and stored in DynamoDB at two levels:
- Field-level options — specified directly on the
fieldmacro (such asstore_as_string: trueorstore_as_native_binary: true). - Global configuration defaults — configured application-wide in an initializer (such as
config.store_datetime_as_string = true).
Field-level declarations always take precedence over global settings. If a field-level option is omitted, Dynamoid falls back to the corresponding global configuration setting.
Configuration Reference
The following table catalogs all configuration options that govern attribute serialization, type casting, and storage formats:
| Global Option | Default Value | Per-Field Override |
|---|---|---|
store_boolean_as_native | true | store_as_native_boolean |
store_datetime_as_string | false | store_as_string |
store_date_as_string | false | store_as_string |
store_binary_as_native | false | store_as_native_binary |
store_attribute_with_nil_value | false | — |
store_empty_string_as_nil | true | — |
convert_big_decimal | false | — |
application_timezone | :utc | — |
dynamodb_timezone | :utc | — |
use_yaml_unsafe_load | false | — |
yaml_permitted_classes | [Symbol, Set, Date, Time, DateTime] | — |
Historical Background
Several storage configuration options exist because Amazon DynamoDB’s data model evolved significantly after its initial release in 2012. As DynamoDB introduced new capabilities, Dynamoid added configuration options to adopt the new database behavior while preserving backward compatibility for existing data.
When DynamoDB launched in 2012, it supported only strings and numbers (with binary data added later that year) and had no concept of booleans, nulls, lists, or maps. Dynamoid originally stored booleans as 't' and 'f' strings, and omitted or removed attributes assigned nil.
In October 2014, DynamoDB added native booleans, explicit nulls, and document types (lists and maps). Dynamoid added store_boolean_as_native to support native booleans while maintaining compatibility with legacy data, and store_attribute_with_nil_value to optionally persist explicit null attributes.
In May 2020, DynamoDB added support for empty strings. Because DynamoDB originally rejected empty strings, Dynamoid had always converted them to nil. Dynamoid introduced store_empty_string_as_nil (defaulting to true for backward compatibility) so applications can opt into persisting empty strings as-is.
Nil Attributes
When a model attribute has a nil value, Dynamoid can store it in DynamoDB in two ways: by omitting the attribute entirely, or by persisting an explicit NULL value. By default, Dynamoid omits or removes attributes with nil values, preserving the original DynamoDB behavior from before native NULL support was added.
Omitting nil attributes saves storage and throughput: because both attribute names and values contribute to item size in DynamoDB, writing explicit NULL values increases payload size and consumes extra read and write capacity.
Omitting nil attributes is also required for secondary index keys. DynamoDB index keys only accept String, Number, or Binary values and reject NULL—persisting an explicit NULL to an indexed attribute raises an error. Omitting nil attributes avoids this error and allows secondary indexes to act as sparse indexes.
If your application or external integrations require explicit null values, enable store_attribute_with_nil_value:
Dynamoid.configure do |config|
config.store_attribute_with_nil_value = true
end
When enabled, attributes with nil values are persisted as explicit DynamoDB null (NULL) attributes.
Numbers in Nested Structures
By default, numbers inside nested structures (such as :map and :raw fields) reload from DynamoDB as BigDecimal instances to avoid losing numeric precision:
user = User.create!(settings: { limit: 100, ratio: 0.75 })
user.reload.settings
# => { limit: BigDecimal("100"), ratio: BigDecimal("0.75") }
If BigDecimal objects cause friction with JSON serialization or float calculations, enable convert_big_decimal to convert them to standard floats when loading items:
Dynamoid.configure do |config|
config.convert_big_decimal = true
end
user.reload.settings
# => { limit: 100.0, ratio: 0.75 }
Time Zones
For :datetime fields, Dynamoid separates the time zone used in your application from the time zone used when storing timestamps as ISO-8601 strings in DynamoDB, configured via application_timezone and dynamodb_timezone:
Dynamoid.configure do |config|
config.application_timezone = 'America/New_York'
config.dynamodb_timezone = :utc
config.store_datetime_as_string = true
end
Strings without an explicit time zone offset are interpreted in application_timezone when assigned, normalized to dynamodb_timezone when stored, and converted back to application_timezone when loaded:
order = Order.create!(placed_at: '2026-10-15 16:00:00')
order.placed_at # => 2026-10-15T16:00:00-04:00
order.reload.placed_at # => 2026-10-15T16:00:00-04:00
# DynamoDB item attribute:
# "placed_at": "2026-10-15T20:00:00+00:00"
When storing timestamps as strings, Dynamoid normalizes values to dynamodb_timezone (UTC by default). Because ISO-8601 strings sort alphabetically, uniform normalization ensures range queries (between, gt, lt) and chronological sorting work reliably.
YAML Deserialization
When using :serialized without an explicit serializer, Dynamoid uses YAML for attribute encoding and decoding.
Following modern Ruby security practices, Dynamoid uses YAML.safe_load by default to prevent arbitrary code execution vulnerabilities. The default permitted classes are [Symbol, Set, Date, Time, DateTime].
If a serialized attribute contains an unlisted class, deserialization raises a Psych::DisallowedClass exception. To allow additional classes, add them to yaml_permitted_classes in an initializer:
Dynamoid.configure do |config|
config.yaml_permitted_classes += [MyClass]
end
Alternatively, if your application runs in a trusted environment and requires unrestricted deserialization of arbitrary object graphs, enable use_yaml_unsafe_load:
Dynamoid.configure do |config|
config.use_yaml_unsafe_load = true
end
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.
Associations
An association is a connection between two Dynamoid models. Most applications work with domain entities that relate to one another: an author writes many books, a user has one profile, or students enroll in multiple courses.
Dynamoid provides class-level association macros—modeled after Rails Active Record—to declare one-to-one, one-to-many, and many-to-many relationships between models. Declaring an association tells Dynamoid how two models are connected, automatically generates the underlying foreign key fields, and adds convenience methods to link, query, and delete related models.
Important
Associations are only supported for models with a simple primary key (partition key only). Models that declare a sort key cannot declare associations or be referenced by associations on other models.
Associations Overview
Without Associations
To see why associations are useful, consider an application with Author and Book models where each author can have many books. Without associations, you have to declare foreign key fields and coordinate every cross-model operation by hand:
class Author
include Dynamoid::Document
field :name
end
class Book
include Dynamoid::Document
field :title
field :author_id
end
To create a book for an existing author, you must manually pass the author’s partition key (author.id):
author = Author.create(name: 'Ursula K. Le Guin')
book = Book.create(title: 'A Wizard of Earthsea', author_id: author.id)
To retrieve all books written by that author, you have to construct an explicit query using author.id:
books = Book.where(author_id: author.id).all
And if you want to delete an author along with all of their books, you must manually query the books, iterate through them to destroy each one, and then destroy the author:
books = Book.where(author_id: author.id).all
books.each(&:destroy)
author.destroy
Using Associations
With Dynamoid associations, you express the relationship between Author and Book declaratively on the model classes:
class Author
include Dynamoid::Document
has_many :books
field :name
end
class Book
include Dynamoid::Document
belongs_to :author
field :title
end
With this declaration in place, creating a new book for an author no longer requires passing foreign keys manually:
author = Author.create(name: 'Ursula K. Le Guin')
book = author.books.create(title: 'A Wizard of Earthsea')
Navigating between related models in either direction uses natural reader methods:
author.books.all # => [#<Book id: "...", title: "A Wizard of Earthsea", ...>]
book.author # => #<Author id: "...", name: "Ursula K. Le Guin", ...>
And destroying all of an author’s books is reduced to a single method call on the collection:
author.books.destroy_all
author.destroy
Important
Unlike Active Record—where assigning an association only updates an in-memory attribute until
saveis called—modifying an association in Dynamoid immediately saves the changes to DynamoDB. Models passed to=or<<must already be persisted so their partition key is present. In addition, because association mutation methods (=,<<,create,delete, etc.) persist changes by callingupdate_attribute, any unsaved attribute changes pending on either model instance will also be written to DynamoDB.
Types of Associations
Dynamoid supports four types of associations:
belongs_to
A belongs_to association sets up a connection with another model such that each instance of the declaring model belongs to one instance of the target model. For example, if your application includes authors and books, and each book is written by a single author, declare belongs_to :author on the Book model:
class Book
include Dynamoid::Document
belongs_to :author
field :title
end
Unlike relational databases that require migrations to add foreign key columns, belongs_to automatically declares the underlying foreign key field on the model—you do not need to declare a separate field for it.
Note
belongs_toassociations must use a singular name. Because Dynamoid infers the target class name by classifying the association name, declaringbelongs_to :authorswould look for anAuthorsclass instead ofAuthor.
belongs_to can be used in either a one-to-one relationship (paired with has_one on the other model) or a one-to-many relationship (paired with has_many on the other model). When used alone, belongs_to creates a one-directional relationship: each Book knows its Author, but Author instances do not know about their books. To set up a bidirectional association, combine belongs_to with has_one or has_many on the Author model.
Methods Added by belongs_to
When you declare a belongs_to association, the declaring class automatically gains two methods related to the association:
<association><association>=(model)
In both methods, <association> is replaced with the symbol passed as the first argument to belongs_to. For belongs_to :author, a Book instance gains book.author and book.author=.
Calling book.author returns an association proxy rather than the Author instance directly. The proxy exposes the following methods to manage the association:
<association>.create(attributes)<association>.create!(attributes)<association>.delete<association>.target<association>.loaded?<association>.reset
Returning a proxy allows you to call methods like book.author.create or book.author.delete even when no author is currently linked. On first access, the proxy lazily loads the associated Author model and forwards all other method calls directly to it.
Reading the Association
The <association> method returns the associated model, or nil if no associated model is found:
author = book.author
Because the proxy forwards method calls to the target model, you can call Author methods directly on book.author:
book.author.update_attribute(:name, 'Ursula K. Le Guin')
If the associated model has already been retrieved from DynamoDB, the cached version is returned. To clear the cached model so the next access fetches it from DynamoDB again, call reset:
book.author.reset
Assigning and Creating
The <association>= method links an existing model to this model:
book.author = author
The <association>.create method instantiates a new model of the target class, saves it to DynamoDB, and links it to this model:
author = book.author.create(name: 'Ursula K. Le Guin')
The <association>.create! method does the same, but raises a validation error if the target model is invalid:
author = book.author.create!(name: 'Ursula K. Le Guin')
Removing the Association
To unlink the associated model without deleting its item from DynamoDB, call delete on the association proxy or assign nil:
book.author.delete
book.author = nil
Checking Presence
You can check whether an associated model exists using nil?, blank?, or present?:
book.author.nil? # => true
book.author.blank? # => true
book.author.present? # => false
has_one
A has_one association sets up a one-to-one relationship with another model, where each instance of the declaring model is associated with at most one instance of the target model. For example, if each user in your application has a single profile, declare has_one :profile on the User model:
class User
include Dynamoid::Document
has_one :profile
field :email
end
Note
has_oneassociations must use a singular name. Because Dynamoid infers the target class name by classifying the association name, declaringhas_one :profileswould look for aProfilesclass instead ofProfile.
When used alone, has_one creates a one-directional relationship: each User knows its Profile, but Profile instances do not know about their user. To set up a bidirectional association, combine has_one with belongs_to on the Profile model.
Methods Added by has_one
When you declare a has_one association, the declaring class automatically gains two methods related to the association:
<association><association>=(model)
In both methods, <association> is replaced with the symbol passed as the first argument to has_one. For has_one :profile, a User instance gains user.profile and user.profile=.
Calling user.profile returns an association proxy rather than the Profile instance directly. The proxy exposes the following methods to manage the association:
<association>.create(attributes)<association>.create!(attributes)<association>.delete<association>.target<association>.loaded?<association>.reset
Returning a proxy allows you to call methods like user.profile.create or user.profile.delete even when no profile is currently linked. On first access, the proxy lazily loads the associated Profile model and forwards all other method calls directly to it.
Reading the Association
The <association> method returns the associated model, or nil if no associated model is found:
profile = user.profile
Because the proxy forwards method calls to the target model, you can call Profile methods directly on user.profile:
user.profile.update_attribute(:bio, 'Mathematician')
If the associated model has already been retrieved from DynamoDB, the cached version is returned. To clear the cached model so the next access fetches it from DynamoDB again, call reset:
user.profile.reset
Assigning and Creating
The <association>= method links an existing model to this model:
user.profile = profile
The <association>.create method instantiates a new model of the target class, saves it to DynamoDB, and links it to this model:
profile = user.profile.create(bio: 'Mathematician')
The <association>.create! method does the same, but raises a validation error if the target model is invalid:
profile = user.profile.create!(bio: 'Mathematician')
Removing the Association
To unlink the associated model without deleting its item from DynamoDB, call delete on the association proxy or assign nil:
user.profile.delete
user.profile = nil
Checking Presence
You can check whether an associated model exists using nil?, blank?, or present?:
user.profile.nil? # => true
user.profile.blank? # => true
user.profile.present? # => false
has_many
A has_many association sets up a one-to-many connection with other models, where each instance of the declaring model is associated with zero or more instances of the target model. For example, if an author can have many books, declare has_many :books on the Author model:
class Author
include Dynamoid::Document
has_many :books
field :name
end
Note
has_manyassociations must use a plural name. Dynamoid infers the target class name by singularizing and classifying the association name, so:booksresolves toBook.
When used alone, has_many creates a one-directional relationship: each Author knows its books, but Book instances do not know about their author. To set up a bidirectional association, combine has_many with belongs_to on the Book model.
Methods Added by has_many
When you declare a has_many association, the declaring class automatically gains two methods related to the association:
<association><association>=(models)
In both methods, <association> is replaced with the symbol passed as the first argument to has_many. For has_many :books, an Author instance gains author.books and author.books=.
Calling author.books returns an association proxy rather than an Array directly. The proxy includes Enumerable and exposes the following methods to manage the collection:
<association>.all<association> << model<association>.create(attributes)<association>.create!(attributes)<association>.delete(model)<association>.delete_all<association>.destroy_all<association>.target<association>.loaded?<association>.reset
On first access, the proxy lazily loads the associated Book models and forwards all other method calls directly to the underlying Array.
Reading the Association
The <association>.all method returns an array of all associated models, or an empty array ([]) if none are linked:
books = author.books.all
Because the proxy includes Enumerable and forwards method calls to the underlying Array, you can call Array and Enumerable methods directly on author.books:
first_book = author.books.first
titles = author.books.map(&:title)
If the associated models have already been retrieved from DynamoDB, the cached collection is returned. To clear the cached collection so the next access fetches the models from DynamoDB again, call reset:
author.books.reset
Assigning and Creating
The <association> << method appends an existing model (or an array of models) to the collection while preserving existing links:
author.books << book
author.books << [book1, book2]
The <association>= method replaces the entire collection with the given model or array of models, unlinking any previously associated models:
author.books = [book1, book2]
The <association>.create method instantiates a new model of the target class, saves it to DynamoDB, and adds it to the collection:
book = author.books.create(title: 'A Wizard of Earthsea')
The <association>.create! method does the same, but raises a validation error if the target model is invalid:
book = author.books.create!(title: 'A Wizard of Earthsea')
Removing the Association
To unlink a specific model (or an array of models) from the collection without deleting its item from DynamoDB, call delete:
author.books.delete(book)
To unlink all associated models without deleting their items from DynamoDB, assign []:
author.books = []
To unlink all associated models and delete their items from DynamoDB without running callbacks, call delete_all:
author.books.delete_all
To unlink all associated models and destroy their items in DynamoDB (running destroy callbacks on each target model), call destroy_all:
author.books.destroy_all
Checking Presence
You can check whether the collection has any associated models or contains a specific model using empty?, blank?, present?, or include?:
author.books.empty? # => true
author.books.blank? # => true
author.books.present? # => false
author.books.include?(book) # => false
has_and_belongs_to_many
A has_and_belongs_to_many association sets up a direct many-to-many connection with other models, where each instance of the declaring model is associated with zero or more instances of the target model, and vice versa. For example, if students enroll in multiple courses and each course has multiple students, declare has_and_belongs_to_many :courses on the Student model:
class Student
include Dynamoid::Document
has_and_belongs_to_many :courses
field :name
end
Unlike relational databases that require an intermediate join table to represent many-to-many relationships, has_and_belongs_to_many does not require a join table or join model.
Note
has_and_belongs_to_manyassociations must use a plural name. Dynamoid infers the target class name by singularizing and classifying the association name, so:coursesresolves toCourse.
When used alone, has_and_belongs_to_many creates a one-directional relationship: each Student knows its courses, but Course instances do not know about their students. To set up a bidirectional association, declare has_and_belongs_to_many :students on the Course model as well.
Methods Added by has_and_belongs_to_many
When you declare a has_and_belongs_to_many association, the declaring class automatically gains two methods related to the association:
<association><association>=(models)
In both methods, <association> is replaced with the symbol passed as the first argument to has_and_belongs_to_many. For has_and_belongs_to_many :courses, a Student instance gains student.courses and student.courses=.
Calling student.courses returns an association proxy rather than an Array directly. The proxy includes Enumerable and exposes the following methods to manage the collection:
<association>.all<association> << model<association>.create(attributes)<association>.create!(attributes)<association>.delete(model)<association>.delete_all<association>.destroy_all<association>.target<association>.loaded?<association>.reset
On first access, the proxy lazily loads the associated Course models and forwards all other method calls directly to the underlying Array.
Reading the Association
The <association>.all method returns an array of all associated models, or an empty array ([]) if none are linked:
courses = student.courses.all
Because the proxy includes Enumerable and forwards method calls to the underlying Array, you can call Array and Enumerable methods directly on student.courses:
first_course = student.courses.first
titles = student.courses.map(&:title)
If the associated models have already been retrieved from DynamoDB, the cached collection is returned. To clear the cached collection so the next access fetches the models from DynamoDB again, call reset:
student.courses.reset
Assigning and Creating
The <association> << method appends an existing model (or an array of models) to the collection while preserving existing links:
student.courses << course
student.courses << [course1, course2]
The <association>= method replaces the entire collection with the given model or array of models, unlinking any previously associated models:
student.courses = [course1, course2]
The <association>.create method instantiates a new model of the target class, saves it to DynamoDB, and adds it to the collection:
course = student.courses.create(title: 'Distributed Systems')
The <association>.create! method does the same, but raises a validation error if the target model is invalid:
course = student.courses.create!(title: 'Distributed Systems')
Removing the Association
To unlink a specific model (or an array of models) from the collection without deleting its item from DynamoDB, call delete:
student.courses.delete(course)
To unlink all associated models without deleting their items from DynamoDB, assign []:
student.courses = []
To unlink all associated models and delete their items from DynamoDB without running callbacks, call delete_all:
student.courses.delete_all
To unlink all associated models and destroy their items in DynamoDB (running destroy callbacks on each target model), call destroy_all:
student.courses.destroy_all
Checking Presence
You can check whether the collection has any associated models or contains a specific model using empty?, blank?, present?, or include?:
student.courses.empty? # => true
student.courses.blank? # => true
student.courses.present? # => false
student.courses.include?(course) # => false
Association Options
While default conventions infer the target class and corresponding association names automatically, association macros accept options to customize target classes, inverse relationships, and foreign key storage:
| Option | Supported Macros | Description |
|---|---|---|
:class_name | All | Specifies the target class name as a String |
:class | All | Specifies the target class constant directly |
:inverse_of | All | Specifies the name of the corresponding association on the target class |
:foreign_key | belongs_to | Stores the target partition key in a scalar field instead of a Set |
:class_name or :class
By default, Dynamoid infers the target class from the association name—e.g. :author to Author. If an association uses a custom name, specify the target class explicitly using :class_name as a string or :class as a class constant:
class Book
include Dynamoid::Document
belongs_to :writer, class_name: 'Author'
field :title
end
Specifying the target class as a String via :class_name is generally recommended because it defers constant resolution until the association is first accessed. Passing a class constant directly (class: Author) resolves the constant immediately while the class definition is evaluated, which can trigger circular autoloading issues if both models reference each other during boot.
:inverse_of
Dynamoid synchronizes bidirectional associations by inferring the corresponding association name from the declaring model’s class name—e.g. Author looks for an :author association on Book.
When an association uses a custom name that cannot be inferred automatically, specify :inverse_of so Dynamoid knows which matching association to update:
class Author
include Dynamoid::Document
has_many :publications, class_name: 'Book', inverse_of: :writer
field :name
end
class Book
include Dynamoid::Document
belongs_to :writer, class_name: 'Author', inverse_of: :publications
field :title
end
author = Author.create(name: 'Ursula K. Le Guin')
book = Book.create(title: 'A Wizard of Earthsea')
book.writer = author
author.publications.include?(book) # => true
:foreign_key
By default, belongs_to :author automatically names and declares the foreign key field. Pass the :foreign_key option to set the attribute name directly and store the key as a scalar value:
class Book
include Dynamoid::Document
belongs_to :author, foreign_key: :author_id
field :title
end
author = Author.create(name: 'Ursula K. Le Guin')
book = Book.create(title: 'A Wizard of Earthsea')
book.author = author
book.author_id # => "a8f5c3..."
book.author # => #<Author id: "a8f5c3...", name: "Ursula K. Le Guin", ...>
Passing :foreign_key configures two behaviors:
- Declares a field with the specified name (avoiding the need to declare
field :author_idseparately). - Automatically sets the field type to match the partition key type of the target model (e.g.
:stringor:integer).
Tip
Dynamoid does not store foreign keys as scalar values by default (for details, see How Associations Are Stored). Because DynamoDB secondary indexes require scalar attributes, use
foreign_key:onbelongs_towhenever you plan to declare a Global or Local Secondary Index on the foreign key attribute.
The :foreign_key option is only supported on belongs_to. Because Dynamoid inspects the target model’s partition key type when evaluating the declaration, the target class must be defined or autoloadable when belongs_to ..., foreign_key: ... runs.
Tips and Warnings
Bidirectional Synchronization
When you declare an association on only one model, the relationship is one-directional. For example, if Book declares belongs_to :author but Author does not declare has_many :books, you can access book.author, but Author instances have no author.books method.
When you declare corresponding associations on both models—such as has_many :books on Author and belongs_to :author on Book—Dynamoid automatically keeps both sides synchronized whenever you link or unlink models from either side.
Assigning the association on book automatically adds book to author.books:
author = Author.create(name: 'Ursula K. Le Guin')
book = Book.create(title: 'A Wizard of Earthsea')
book.author = author
author.books.include?(book) # => true
Likewise, adding or removing book through author.books automatically updates book.author:
author.books.delete(book)
book.reload.author # => nil
The same bidirectional synchronization applies to has_one paired with belongs_to, and to has_and_belongs_to_many declared on both models.
Validating Associations
Unlike Rails Active Record and Mongoid—where belongs_to requires the associated model to be present by default unless optional: true is specified—all associations in Dynamoid (including belongs_to) are optional by default.
To require that an association is present before saving, add a standard ActiveModel presence validation on the association name:
class Book
include Dynamoid::Document
belongs_to :author
field :title
validates :author, presence: true
end
Deletion and Disassociation
When you delete a model instance with #delete or #destroy, Dynamoid automatically iterates over its declared associations and removes its partition key from all linked models in DynamoDB:
author = Author.create(name: 'Ursula K. Le Guin')
book = author.books.create(title: 'A Wizard of Earthsea')
book.destroy
author.reload.books.empty? # => true
Class-level deletion (Book.delete(book.id)) deletes the item directly by key without instantiating the model, so it does not update references on linked models. If a referenced item no longer exists in DynamoDB, accessing a belongs_to or has_one association returns nil, and has_many or has_and_belongs_to_many silently omits the missing item rather than raising Dynamoid::Errors::RecordNotFound.
Caching and Reloading
While calling reset on an association proxy (book.author.reset or author.books.reset) clears the cached target for that single association, calling reload on the parent model refreshes the model’s attributes from DynamoDB and resets all of its cached associations at once:
author.books.all
author.books.loaded? # => true
author.reload
author.books.loaded? # => false
Modifying the underlying foreign key attribute directly via write_attribute or []= (for example, author[:books_ids] = ...) also resets the cached association.
Querying and Filtering with Secondary Indexes
Use associations for bounded relationships—such as a user’s profile, an author’s books, or a student’s courses—where loading the entire collection into memory is fast and convenient.
When you need to filter related models at the database level, or when modeling high-cardinality relationships (such as a customer with thousands of orders), avoid has_many. Instead, declare a Global Secondary Index on the foreign key and query the target table directly via the Query Interface:
class Book
include Dynamoid::Document
belongs_to :author, foreign_key: :author_id
field :title
field :published_at, :datetime
global_secondary_index hash_key: :author_id, range_key: :published_at
end
Book.where(author_id: author.id, 'published_at.gt': 1.year.ago).all
How Associations Are Stored
When designing associations in Dynamoid, an intentional decision was made that fetching associated models by foreign keys would not rely on or require Secondary Indexes. In DynamoDB, looking up items by an unindexed foreign key requires an expensive full-table scan, while Global Secondary Indexes demand careful capacity provisioning, add storage and write costs, and introduce operational overhead.
Instead of querying a secondary index by foreign key, Dynamoid caches the partition keys of associated models directly on the declaring item inside a DynamoDB Set attribute. Loading an association then uses fast direct point fetching or batch point fetching without scanning tables or querying secondary indexes.
This storage strategy involves two deliberate simplifications:
- Sets for all associations —
has_oneandbelongs_toalso use an<association>_idsset attribute, holding a single partition key. - Simple primary keys only — because DynamoDB sets only hold scalar values, models with composite primary keys cannot use associations.
For Author (has_many :books) and Book (belongs_to :author), linking models stores the following attributes on their DynamoDB items:
author = Author.create(name: 'Ursula K. Le Guin')
book = author.books.create(title: 'A Wizard of Earthsea')
author.books_ids # => #<Set: {"b92d1e..."}>
book.author_ids # => #<Set: {"f41a8c..."}>
If Book specifies belongs_to :author, foreign_key: :author_id, the Book item stores the partition key as a scalar string under author_id instead:
book.author_id # => "f41a8c..."
Storing the foreign key as a scalar attribute is necessary if you plan to index it with a Global Secondary Index, as DynamoDB does not allow indexing Set attributes.
Relying on cached IDs rather than secondary indexes creates two trade-offs:
- Item size growth — each linked model adds an ID to
<association>_ids, increasing payload size toward the 400 KB item limit. - Outdated cached IDs — creating or deleting items via class-level persistence methods (such as
import,upsert,delete, ordelete_all) or outside Dynamoid does not update the associated model’s cached ID set.
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.
Single Table Inheritance
The Single Table Inheritance (STI) pattern maps an entire class hierarchy to a single DynamoDB table. An inheritance attribute (or discriminator)—by default named type—stores the class name for each item, allowing Dynamoid to instantiate the correct Ruby class when loading an item.
This pattern is useful when models share common fields and identity but require specialized behavior or extra attributes. For example, cars and trucks share baseline attributes like VIN and make, but cars define passenger seats while trucks specify cargo capacity.
Inheritance Hierarchy
To set up Single Table Inheritance, create a base model and declare the type field. Subclasses inherit from the base model using standard Ruby inheritance:
class Vehicle
include Dynamoid::Document
field :make
field :model
field :type
end
class Car < Vehicle
field :seats, :integer
end
class Truck < Vehicle
field :cargo_capacity, :integer
end
Subclasses inherit all fields, associations, callbacks, and validations declared on the parent model, while any declared on a subclass apply only to that subclass and its descendants. Because the entire hierarchy shares the base model’s DynamoDB table, declare table options (table) and secondary indexes on the base model:
Vehicle.table_name # => "vehicles"
Car.table_name # => "vehicles"
Truck.table_name # => "vehicles"
Important
Unlike Active Record, where the underlying database table defines columns, Dynamoid requires an explicit
field :typedeclaration on the base model. If this field is omitted, Dynamoid will not assign type values or filter queries by type.
Polymorphic Persistence and Querying
When initializing or saving models, instantiate the specific subclass directly. Dynamoid populates the type attribute automatically so you never need to set type values by hand:
car = Car.create(make: 'Honda', model: 'Civic', seats: 5)
car.type # => "Car"
truck = Truck.create(make: 'Ford', model: 'F-150', cargo_capacity: 2000)
truck.type # => "Truck"
If you need to instantiate a model dynamically from an attributes hash that contains the type attribute, use build (or create) on the base class rather than new:
vehicle = Vehicle.build(type: 'Car', make: 'Honda', model: 'Civic', seats: 5)
vehicle.class # => Car
Loading an item through the base class returns an instance of the specific subclass:
vehicle = Vehicle.find(car.id)
vehicle.class # => Car
vehicle.seats # => 5
Querying through the base class searches across the entire hierarchy and instantiates each returned item as its specific subclass:
vehicles = Vehicle.all
hondas = Vehicle.where(make: 'Honda').all
Conversely, querying through a subclass restricts results to that class and its descendants:
cars = Car.all
honda_cars = Car.where(make: 'Honda').all
Inheritance Field Configuration
If your table already uses type for another domain attribute, or if you prefer a different attribute name, configure :inheritance_field in the table method on the base model and declare the corresponding field:
class Vehicle
include Dynamoid::Document
table inheritance_field: :vehicle_type
field :vehicle_type
end
class Car < Vehicle
end
car = Car.create
car.vehicle_type # => "Car"
Class Mapping and Resolution
To decouple database type values from Ruby class names, override sti_name on subclasses and map them with sti_class_for on the base model:
class Vehicle
include Dynamoid::Document
field :type
def self.sti_class_for(type_name)
case type_name
when 'sedan' then Car
when 'pickup' then Truck
else
super
end
end
end
class Car < Vehicle
def self.sti_name
'sedan'
end
end
class Truck < Vehicle
def self.sti_name
'pickup'
end
end
Calling super in the else branch falls back to default constant lookup, resolving standard class names (such as 'Vehicle' or subclasses without a custom sti_name) and raising Dynamoid::Errors::SubclassNotFound for unknown values.
Subclasses persist using their custom identifiers, and Vehicle.find resolves them back to their respective classes:
car = Car.create
car.type # => "sedan"
truck = Truck.create
truck.type # => "pickup"
Vehicle.find(car.id).class # => Car
Vehicle.find(truck.id).class # => Truck
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.
Query Interface
If you are accustomed to querying DynamoDB with the AWS SDK, retrieving data typically requires constructing low-level parameter hashes for operations like GetItem, BatchGetItem, Query, and Scan. Dynamoid provides an expressive, chainable query interface modeled after Active Record, abstracting low-level SDK calls while adapting to DynamoDB’s partitioning and indexing model.
Similar to Active Record relations, Dynamoid queries evaluate lazily. Calling query methods like where builds a chainable query without executing network requests against DynamoDB until you iterate over results, access an item, or call an execution method such as all or each.
query = User.where(active: true)
query.each do |user|
puts user.name
end
Code examples throughout this guide refer to the following models:
class User
include Dynamoid::Document
field :name
field :email
field :active, :boolean
end
class OrderItem
include Dynamoid::Document
table key: :order_id
range :position, :integer
field :product_id
field :quantity, :integer
end
The User model represents a simple primary key table using Dynamoid’s default id partition key. The OrderItem model represents a composite primary key table: table key: :order_id declares a custom partition key (without needing an explicit field call), and range :position, :integer defines the sort key. For details on declaring primary keys, see Partition Key.
Retrieving Items
Dynamoid provides finder methods to look up individual items by primary key or iterate over collections from a table.
Retrieving a Single Item
Use find to look up an item by its partition key. If no matching item exists, Dynamoid raises Dynamoid::Errors::RecordNotFound:
user = User.find('3a9f7216-4726-4aea-9fbc-8554ae9292cb')
# => #<User id: "3a9f7216...", name: "Alice", active: true>
You can also retrieve multiple items at once by passing multiple keys as separate arguments:
users = User.find('3a9f7216-4726-4aea-9fbc-8554ae9292cb', 'b2c89f14-8742-4b8a-9e11-7394851239aa')
# => [#<User id: "3a9f7216...", name: "Alice", active: true>, #<User id: "b2c89f14...", name: "Bob", active: false>]
Or as an array:
users = User.find(%w[3a9f7216-4726-4aea-9fbc-8554ae9292cb b2c89f14-8742-4b8a-9e11-7394851239aa])
# => [#<User id: "3a9f7216...", name: "Alice", active: true>, #<User id: "b2c89f14...", name: "Bob", active: false>]
Warning
Dynamoid raises
Dynamoid::Errors::RecordNotFoundif any of the requested items cannot be found. The order of items in the returned array is not guaranteed to match the order of the supplied IDs.
When a table uses a composite primary key, pass the sort key via the range_key: keyword argument. Omitting the sort key raises Dynamoid::Errors::MissingRangeKey:
order_item = OrderItem.find(order_id, range_key: 1)
# => #<OrderItem order_id: "d7e34b12...", position: 1, product_id: "c3d4e5f6...", quantity: 2>
For composite primary keys, retrieve multiple items by passing an array of [partition_key, sort_key] pairs:
order_items = OrderItem.find([[order_id, 1], [order_id, 2]])
# => [#<OrderItem order_id: "d7e34b12...", position: 1, product_id: "c3d4e5f6...", quantity: 2>, #<OrderItem order_id: "d7e34b12...", position: 2, product_id: "e8f45c23...", quantity: 1>]
Retrieving Multiple Items
Use all to retrieve an entire table or query results. Rather than loading the entire collection into memory upfront, all returns a lazy enumerator that fetches pages from DynamoDB on demand:
users = User.all
active_users = User.where(active: true).all
To iterate over items directly as they stream from DynamoDB, use each:
User.where(active: true).each do |user|
puts user.name
end
To load all matching items into a Ruby array immediately, call to_a:
users = User.where(active: true).all.to_a
# => [#<User id: "3a9f7216...", name: "Alice", active: true>, #<User id: "b2c89f14...", name: "Bob", active: true>]
Strongly Consistent Reads
By default, DynamoDB read operations are eventually consistent. A read request performed immediately after a write might return stale data while changes propagate across DynamoDB storage partitions. When your application requires the latest data, you can request strongly consistent reads.
For single-item lookups and batch retrieval with find, pass consistent_read: true:
user = User.find(user_id, consistent_read: true)
When building a query, append consistent:
users = User.where(active: true).consistent.all
Note
Strongly consistent reads consume double the Read Capacity Units (RCUs) of eventually consistent reads. In addition, DynamoDB does not support strongly consistent reads on Global Secondary Indexes (GSIs).
Filtering Items
Use where to filter items, passing conditions either as a hash or as a string. Which attributes and operators you provide determines whether Dynamoid executes a fast partition Query or a full-table Scan (see When Query and Scan Execute).
Hash Conditions
Passing a hash specifies equality conditions:
users = User.where(active: true).all
# => [#<User id: "3a9f7216...", name: "Alice", active: true>]
When specifying multiple attributes in a hash, Dynamoid combines them with AND logic:
users = User.where(name: 'Alice', active: true).all
# => [#<User id: "3a9f7216...", name: "Alice", active: true>]
Dynamoid automatically type-casts condition values based on the model’s declared field types.
To express conditions other than equality, append an operator to the attribute name using dot notation (attribute.operator):
order_items = OrderItem.where('quantity.gt': 1).all
# => [#<OrderItem order_id: "3a9f7216...", position: 1, product_id: "c3d4e5f6...", quantity: 2>]
Dynamoid supports the following predicate operators:
| Operator | Meaning | Example |
|---|---|---|
gt | Greater than (>) | 'quantity.gt': 5 |
gte | Greater than or equal (>=) | 'quantity.gte': 5 |
lt | Less than (<) | 'quantity.lt': 20 |
lte | Less than or equal (<=) | 'quantity.lte': 20 |
ne | Not equal (<>) | 'name.ne': 'Alice' |
between | Value falls within range [min, max] | 'quantity.between': [5, 15] |
in | Value is included in a list | 'name.in': %w[Alice Bob] |
begins_with | String starts with prefix | 'name.begins_with': 'Al' |
contains | Substring match, or element in array/set | 'name.contains': 'li' |
not_contains | Substring or element not present | 'name.not_contains': 'admin' |
null | Attribute does not exist on the item | 'active.null': true |
not_null | Attribute exists on the item | 'active.not_null': true |
In DynamoDB, an absent attribute is distinct from an attribute whose value is NULL. By default, Dynamoid does not store attributes with nil values rather than writing an explicit NULL value. To find items where an attribute is absent, use the null operator:
users = User.where('email.null': true).all
# => [#<User id: "3a9f7216...", name: "Alice", email: nil, active: true>]
When attributes with nil values are explicitly stored in DynamoDB as NULL (for example, when store_attribute_with_nil_value is enabled), pass nil as an equality condition:
users = User.where(email: nil).all
# => [#<User id: "3a9f7216...", name: "Alice", email: nil, active: true>]
Note
Hash conditions only support top-level attributes. To reference nested elements of Map or List attributes (such as
address.cityortags[0]), use string conditions.
String Conditions
When hash conditions are not expressive enough, you can pass a condition string written in DynamoDB expression syntax. Because DynamoDB expressions do not allow raw value literals, use named placeholders (:placeholder) in the string and pass their values as a hash in the second argument:
users = User.where('name = :name', name: 'Alice').all
# => [#<User id: "3a9f7216...", name: "Alice", active: true>]
String conditions allow you to combine predicates with AND, OR, NOT, and parentheses:
User.where(
'active = :a AND (name = :n1 OR name = :n2)',
a: true, n1: 'Alice', n2: 'Bob'
).all
They also let you query nested elements inside map and array fields or call DynamoDB functions such as size and attribute_type. For example, given a User model with address and tags fields:
class User
# ...
field :address, :map
field :tags, :array
end
You can filter by a nested map key, an array element at a specific index, or collection size:
User.where('address.city = :city', city: 'Seattle').all
User.where('tags[0] = :tag', tag: 'ruby').all
User.where('size(tags) > :min', min: 1).all
Warning
Unlike hash conditions, Dynamoid does not automatically type-cast placeholder values in string expressions. You must supply values in the exact format expected by DynamoDB (for instance, numeric Unix epoch timestamps for datetime attributes).
Chaining and Merging Conditions
Multiple where calls can be chained together, combining all conditions with AND logic:
users = User.where(active: true).where(name: 'Alice').all
# => [#<User id: "3a9f7216...", name: "Alice", active: true>]
Chained conditions can also target the same attribute when using different operators:
order_items = OrderItem.where('quantity.gte': 2).where('quantity.lte': 10).all
# => [#<OrderItem order_id: "3a9f7216...", position: 1, product_id: "c3d4e5f6...", quantity: 2>]
Hash and string conditions can be combined in the same query chain:
order_items = OrderItem.where(order_id: order_id)
.where('quantity < :min OR quantity > :max', min: 2, max: 10).all
Querying: Query or Scan
In DynamoDB, querying is performed using either an efficient Query operation or a costly Scan. Dynamoid routes your where conditions to one of these operations automatically. Knowing how Dynamoid makes this choice helps you write queries with predictable latency and minimal read cost.
When Query and Scan Execute
Dynamoid inspects conditions passed to where to automatically select the optimal operation:
If conditions include an equality condition on the table’s partition key, Dynamoid executes an efficient Query reading only items within that partition. You can query the partition key alone, narrow the search with a sort key condition, or filter the partition’s items by non-key attributes:
OrderItem.where(order_id: order_id).all
OrderItem.where(order_id: order_id, 'position.gt': 1).all
OrderItem.where(order_id: order_id, quantity: 2).all
Without an equality condition on the partition key, Dynamoid must execute a full-table Scan. This applies when filtering by non-key attributes, querying a sort key alone, or using non-equality operators:
OrderItem.where(quantity: 5).all
OrderItem.where(position: 1).all
OrderItem.where('order_id.ne': order_id).all
By default, Dynamoid logs a warning whenever where triggers a Scan operation, or can be configured to raise an error instead—useful, for example, in test suites to catch accidental scans (see config.warn_on_scan and config.error_on_scan).
Warning
Only hash conditions determine whether Dynamoid performs a
Query. During aQueryoperation, string conditions cannot reference partition or sort keys (of the table or a selected secondary index)—always specify key attributes using hash conditions. In addition, sort key conditions in aQueryonly support a single condition using equality,gt,gte,lt,lte,between, orbegins_with.
Automatic Index Selection
Without an equality condition on the table’s partition key, Dynamoid would normally fall back to a full-table Scan. However, if the model defines a secondary index whose keys match the where conditions, Dynamoid automatically routes the query to that index, executing an efficient Query instead.
To qualify for automatic selection, the index must project all table attributes in DynamoDB and be declared in the model with projected_attributes: :all. This ensures Dynamoid can instantiate complete models directly from the index:
class User
# ...
global_secondary_index hash_key: :email, projected_attributes: :all
end
users = User.where(email: 'alice@example.com').all
# => [#<User id: "3a9f7216...", name: "Alice", email: "alice@example.com">]
If multiple indexes could satisfy the query, Dynamoid prefers composite key matches (partition and sort key) over partition-key-only matches. To eliminate ambiguity and explicitly choose an index, use with_index (see Forcing an Index).
Forcing an Index
When multiple secondary indexes match your where conditions, or when an index uses partial attribute projection (which prevents automatic selection), you can explicitly specify which index to use with with_index.
Given a named secondary index declared on the model (see Secondary Indexes):
class User
# ...
global_secondary_index name: :by_email, hash_key: :email
end
Pass the index name to with_index to route the query to that index:
users = User.where(email: 'alice@example.com').with_index(:by_email).all
You can also use with_index without key conditions to scan a sparse index, reading only items that contain the indexed attribute instead of scanning the entire table:
users = User.with_index(:by_email).all
Ordering Items
In DynamoDB, items cannot be sorted by arbitrary attributes—ordering is strictly determined by the sort key defined on the table or secondary index. By default, DynamoDB returns items in ascending order of the sort key. Pass false to scan_index_forward to sort in descending order (or true for ascending order):
order_items = OrderItem.where(order_id: order_id).scan_index_forward(false).all
# => [
# #<OrderItem order_id: "3a9f7216...", position: 2, product_id: "e8f45c23...", quantity: 1>,
# #<OrderItem order_id: "3a9f7216...", position: 1, product_id: "c3d4e5f6...", quantity: 2>
# ]
Because items are sorted only within a specific partition, ordering requires a partition key condition and is not supported in full table Scan operations.
Warning
DynamoDB sorts strings strictly by UTF-8 binary byte order rather than locale-aware collation. For details on sort order across data types, see the DynamoDB Query API documentation.
Selecting Attributes
By default, queries fetch every attribute for each item. When working with large items or fetching collections, transferring unneeded attributes increases network latency and memory usage. Dynamoid provides two methods to select specific attributes: project and pluck.
project
Use project to retrieve only specific attributes while still receiving model instances. Unprojected attributes are initialized to nil on the loaded models:
users = User.project(:name).all
user = users.first
user.name # => "Alice"
user.active # => nil
Like where, project can be chained with other query methods:
users = User.project(:id, :name).where(active: true).all
# => [#<User id: "3a9f7216...", name: "Alice", email: nil, active: nil, ...>, ...]
pluck
Use pluck to extract attribute values directly into an array without instantiating model objects:
User.where(active: true).pluck(:name)
# => ["Alice", "Bob"]
Passing multiple attribute names returns an array of arrays:
User.where(active: true).pluck(:id, :name)
# => [["3a9f7216...", "Alice"], ["b2c89f14...", "Bob"]]
Unlike project, pluck immediately executes the query and returns an array. Because it skips model instantiation and lifecycle tracking, pluck is significantly faster and uses less memory when extracting data for exports or analytical processing.
Limiting Results
Dynamoid provides two methods to limit query results depending on your application’s needs: scan_limit (to keep read costs strictly bounded) and record_limit (to retrieve a specific number of matching items).
When a query has no filter conditions, every scanned item is a match, so both methods behave identically. When filtering items, they serve different purposes.
scan_limit
Use scan_limit in background jobs, rate-limited tasks, or whenever you need predictable latency and want to cap how many items DynamoDB inspects in storage:
users = User.where(active: true).scan_limit(50).all
Because DynamoDB applies filters after inspecting items, scan_limit guarantees your query will never exceed a set read cost. However, the returned collection may contain fewer items than the limit—or even zero—if few or none of the inspected items pass the filter.
record_limit
Use record_limit when your application logic or UI requires a specific number of matching items, similar to LIMIT in SQL:
users = User.where(active: true).record_limit(10).all
# => [#<User id: "3a9f7216...", name: "Alice", active: true>, ...]
Dynamoid continues fetching items in the background until it collects the requested number of matching items or reaches the end of the data.
Warning
When filtering on attributes with sparse matches,
record_limitmay perform multiple network requests behind the scenes to find enough matching items, leading to higher latency and read costs.
Pagination and Batching
DynamoDB divides query and scan results into pages. Dynamoid provides methods to control page sizes during iteration and to implement cursor-based pagination across requests.
batch
By default, DynamoDB retrieves up to 1 MB of data per request. When iterating over large collections in background jobs or data migrations, unconstrained requests can spike Read Capacity Unit (RCU) consumption and memory usage. Use batch to limit how many items are fetched in each underlying network request:
User.where(active: true).batch(1000).each do |user|
# Process user
end
Like scan_limit, batch limits how many items DynamoDB inspects on each request before filtering. When filters are present, an individual request may return fewer matching items than the specified batch size (or even zero).
find_by_pages
Unlike relational databases, DynamoDB does not support offset-based pagination. Instead, it relies on cursors: each request returns a page of up to 1 MB of data along with a cursor to resume the query if more items remain.
While all and each automatically loop through subsequent pages behind the scenes, find_by_pages yields one native DynamoDB page per network request. This is useful in background jobs where continuous requests might exhaust read capacity and cause throughput throttling, allowing you to process a page of models and pause between requests:
User.where(active: true).find_by_pages do |users, metadata|
# Process page of users
sleep 0.5
end
For stateless pagination across web requests, call find_by_pages without a block to return a lazy enumerator of pages:
pages = User.where(active: true).find_by_pages
users, metadata = pages.first
The client can retain the cursor from metadata[:last_evaluated_key] and send it back in the next request. Pass that cursor to start to fetch the subsequent page (when the final page is reached, metadata[:last_evaluated_key] is nil):
cursor = metadata[:last_evaluated_key]
next_pages = User.where(active: true).start(cursor).find_by_pages
next_users, next_metadata = next_pages.first
Combine find_by_pages with batch or scan_limit to cap the number of items inspected per page:
pages = User.where(active: true).batch(25).find_by_pages
Finding Items with PartiQL
DynamoDB supports PartiQL, a SQL-compatible query language that allows reading and writing items using familiar SQL statements. Use find_by_partiql to execute raw SELECT statements and return instantiated models:
users = User.find_by_partiql(
"SELECT * FROM #{User.table_name} WHERE id = ?",
['3a9f7216-4726-4aea-9fbc-8554ae9292cb']
)
# => [#<User id: "3a9f7216...", name: "Alice", active: true>]
Unlike all and each (which stream items lazily on demand), find_by_partiql eagerly fetches all matching items across paginated DynamoDB responses and returns an Array of instantiated models (converting stored attribute values back to their declared field types and running after_initialize and after_find callbacks).
Note
Dynamoid does not type-cast bind parameter values or convert them to DynamoDB’s underlying storage format; non-native types (such as
:datetimeor: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 asUser.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.
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
#==whencomparable: trueis 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
:datetimeor: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 asUser.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.
Callbacks
Callbacks are hooks into a model’s lifecycle that let you run logic before, after, or around specific events—such as validating attributes, saving an item to DynamoDB, or loading a model into memory.
Defining Callbacks
To register a callback, pass a method name as a symbol:
class User
include Dynamoid::Document
field :email
before_validation :normalize_email
private
def normalize_email
self.email = email.downcase if email.present?
end
end
For short, inline logic that does not need a dedicated method, pass a block instead of a method name. The block executes in the context of the model instance:
class User
include Dynamoid::Document
field :email
before_validation do
self.email = email.downcase if email.present?
end
end
Unlike before_* and after_* callbacks, an around_* callback wraps the underlying event and must yield for the operation to proceed:
class User
include Dynamoid::Document
field :name
around_save :log_save
private
def log_save
puts 'Saving user...'
yield
puts 'User saved'
end
end
Conditional Callbacks
To run a callback only when a specific condition is met, pass the :if or :unless option with a method name symbol:
class User
include Dynamoid::Document
field :email
before_validation :normalize_email, if: :email_present?
private
def email_present?
email.present?
end
def normalize_email
self.email = email.downcase
end
end
For short inline conditions, pass a lambda to :if or :unless. The lambda executes in the context of the model instance:
class User
include Dynamoid::Document
field :email
before_validation :normalize_email, if: -> { email.present? }
private
def normalize_email
self.email = email.downcase
end
end
Halting Execution
To cancel a persistence operation from inside a before_* callback, call throw :abort. Halting the callback chain stops any subsequent callbacks from executing and prevents the write to DynamoDB. Non-bang methods (save, update_attributes, destroy) return false, while bang methods (save!, create!, update_attributes!, destroy!) raise an exception:
class User
include Dynamoid::Document
field :role
before_destroy :prevent_admin_deletion
private
def prevent_admin_deletion
throw(:abort) if role == 'admin'
end
end
user = User.create(role: 'admin')
user.destroy # => false
user.destroy! # Raises Dynamoid::Errors::RecordNotDestroyed
Available Callbacks
Validation
The validation callbacks (before_validation and after_validation) run whenever a model is validated via valid? or before saving (save, create, update_attributes, and Model.update):
class User
include Dynamoid::Document
field :name
before_validation :strip_whitespace
after_validation :log_validation_errors
end
Save
The save callbacks (before_save, around_save, and after_save) run whenever a model is saved (save, create, update_attributes, and Model.update), regardless of whether it is a new model or an already-persisted one:
class User
include Dynamoid::Document
field :name
before_save :prepare_attributes
around_save :wrap_save
after_save :clear_cached_profile
end
Create
The create callbacks (before_create, around_create, and after_create) run only when a new model is persisted to DynamoDB for the first time (save on a new instance, or create):
class User
include Dynamoid::Document
field :name
before_create :assign_defaults
around_create :wrap_create
after_create :send_welcome_email
end
Update
The update callbacks (before_update, around_update, and after_update) run when an existing model is updated (save on a persisted instance, update_attributes, Model.update, or an atomic #update block):
class User
include Dynamoid::Document
field :name
before_update :audit_changes
around_update :wrap_update
after_update :sync_search_index
end
Destroy
The destroy callbacks (before_destroy, around_destroy, and after_destroy) run when a model is destroyed via destroy:
class User
include Dynamoid::Document
field :name
before_destroy :check_dependencies
around_destroy :wrap_destroy
after_destroy :cleanup_storage
end
Initialize and Find
The initialize and find callbacks (after_initialize and after_find) run when models are instantiated in memory: after_initialize runs whenever a model is instantiated (via new or when loaded from DynamoDB), and after_find runs when a model is loaded from DynamoDB:
class User
include Dynamoid::Document
field :name
after_initialize :setup_transient_state
after_find :decrypt_attributes
end
Touch
The touch callback (after_touch) runs after a model’s timestamps are updated via touch:
class User
include Dynamoid::Document
field :name
after_touch :expire_fragment_cache
end
Commit and Rollback
The commit and rollback callbacks (after_commit and after_rollback) run only when a model is mutated inside a Write Transaction—after_commit runs after the transaction succeeds, and after_rollback runs if the transaction fails or is rolled back:
class User
include Dynamoid::Document
field :name
after_commit :publish_event
after_rollback :reset_local_state
end
Callback Order
Because a single persistence operation can trigger multiple lifecycle events, Dynamoid runs their callbacks in a nested sequence.
Creating a Model
When creating a new model (save on a new instance, or create), Dynamoid runs the validation, save, and create callbacks in the following order:
before_validationafter_validationbefore_savearound_save(beforeyield)before_createaround_create(beforeyield)- Item is written to DynamoDB (
yield) around_create(afteryield)after_createaround_save(afteryield)after_save
Updating a Model
When updating an existing model (save on a persisted instance, update_attributes, or Model.update), Dynamoid runs the validation, save, and update callbacks in the following order:
before_validationafter_validationbefore_savearound_save(beforeyield)before_updatearound_update(beforeyield)- Item is updated in DynamoDB (
yield) around_update(afteryield)after_updatearound_save(afteryield)after_save
Destroying a Model
When destroying a model (destroy), Dynamoid runs the destroy callbacks in the following order:
before_destroyaround_destroy(beforeyield)- Item is deleted from DynamoDB (
yield) around_destroy(afteryield)after_destroy
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.
Transactions
DynamoDB transactions provide atomicity, consistency, isolation, and durability (ACID) across one or more items and tables. When you execute a transaction, DynamoDB coordinates all included actions as a single atomic unit—either every operation succeeds and persists, or the entire transaction is cancelled with no partial modifications applied. Operations execute with serializable isolation.
Limitations
DynamoDB transactions are non-interactive batch operations. Instead of running queries interactively and branching based on intermediate results, you define all actions upfront, and DynamoDB executes the entire batch together as an all-or-nothing request. When writing transactional code in Dynamoid, keep the following constraints in mind:
- No interactive read-and-write — operations are executed in a single batch rather than step-by-step.
- Separation of reads and writes — read operations and write operations cannot be combined in the same transaction.
- Item limit — a single transaction can contain at most 100 items.
- Unique item targets — a write transaction cannot perform multiple actions on the same item.
For details on best practices, conflict resolution, and capacity planning, see the Amazon DynamoDB Transactions Developer Guide.
Writing Transactions
Dynamoid models its transactional interface after familiar persistence methods. Start a write transaction on any model class with transaction (or transaction.writing), and invoke persistence methods on the transaction object yielded to the block rather than on a model or class directly.
Transactional counterparts to model instance methods (such as save!, update_attributes!, and destroy) are called as follows:
user = User.new(name: 'Alice')
account = Account.find(account_id)
old_account = Account.find(old_account_id)
User.transaction do |t|
t.save!(user)
t.update_attributes!(account, balance: 250)
t.destroy(old_account)
end
Similarly, transactional counterparts to class methods (such as create!, update_fields, upsert, and delete) are called as follows:
User.transaction do |t|
t.create!(User, name: 'Bob')
t.update_fields(Account, account_id, balance: 500)
t.delete(Account, old_account_id)
end
Note
Operations performed inside a write transaction are queued and not persisted to DynamoDB until the block commits. Reading from DynamoDB inside the block—or inside callbacks such as
after_saveandafter_create—returns the pre-transaction state. To run logic after changes are persisted in DynamoDB, useafter_commitcallbacks (see Commit and Rollback).
Validation and callbacks run immediately when a persistence method is called inside the block. With bang methods (such as save!, create!, and update_attributes!), a validation failure raises an exception, terminating the block and cancelling the entire transaction:
User.transaction do |t|
t.save!(user)
end
To handle invalid models without raising an exception, check valid? or use non-bang methods (such as save, create, and update_attributes), which skip the invalid model and allow the remaining operations in the transaction to proceed:
User.transaction do |t|
account = Account.new(user_id: user.id, balance: 100)
if account.valid?
t.save(account)
end
end
Any unhandled exception raised inside the block cancels the transaction and re-raises the error. To abort a transaction deliberately without propagating an exception, raise Dynamoid::Errors::Rollback. Dynamoid rescues this exception, cancels all queued writes, runs after_rollback callbacks, and exits the block cleanly:
User.transaction do |t|
t.save!(user)
t.update_fields(Account, account_id, balance: 250)
raise Dynamoid::Errors::Rollback if user.suspended?
end
When DynamoDB rejects a transaction—due to a concurrent write conflict, an optimistic locking mismatch, or a duplicate primary key—it cancels the entire batch and raises a single exception instead of RecordNotUnique or StaleObjectError:
begin
User.transaction do |t|
t.create!(User, id: user_id, name: 'Alice')
t.update_fields(Account, account_id, balance: 100)
end
rescue Aws::DynamoDB::Errors::TransactionCanceledException
# Handle conflict, duplicate key, or retry
end
When you cannot wrap all operations in a single block—for example, when accumulating changes across separate methods or objects—you can build a write transaction incrementally and commit it explicitly:
t = Dynamoid::Transactions::Mutation.new
t.create!(User, name: 'Alice')
t.update_fields(Account, account_id, balance: 250)
t.commit
Reading Transactions
Reading transactions retrieve items across one or more tables in a single consistent snapshot. You start a read transaction by calling .transaction.reading on any model class.
Because DynamoDB executes transactional reads in a single batch, calling find inside the block does not load data immediately. Instead, Dynamoid queues each read and fetches all items together when the block exits. You cannot inspect loaded models inside the block itself; once the block completes, it returns an array containing all requested models:
user, account = User.transaction.reading do |t|
t.find(User, user_id)
t.find(Account, account_id)
end
When calling find with arrays of IDs, the transaction returns a single flattened array containing all loaded models in the order requested:
results = User.transaction.reading do |t|
t.find(User, [user_id_1, user_id_2])
t.find(Account, [account_id_1, account_id_2])
end
# => [user_1, user_2, account_1, account_2]
Similarly, you can build a read transaction incrementally without a block:
t = Dynamoid::Transactions::Retrieval.new
t.find(User, user_id)
t.find(Account, account_id)
user, account = t.commit
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.
Configuration
Dynamoid provides application-wide settings for AWS credentials, HTTP networking, retry policies, table provisioning defaults, and field serialization.
Overview
Application settings can be declared in a configuration block or inspected and modified directly at runtime:
require 'dynamoid'
Dynamoid.configure do |config|
config.namespace = 'myapp'
config.region = 'us-west-2'
end
Dynamoid.config.namespace # => "myapp"
Dynamoid.config.region = 'us-east-1'
Ruby on Rails Applications
In Rails applications, place the configuration block in an initializer:
# config/initializers/dynamoid.rb
Dynamoid.configure do |config|
# ...
end
When running in Rails, Dynamoid automatically routes log messages to Rails.logger and derives a default namespace: "dynamoid_#{app_name}_#{Rails.env}".
Standalone Ruby Applications
In standalone scripts, background workers, or non-Rails web frameworks, configure Dynamoid before loading models or issuing queries:
# bootstrap.rb
require 'dynamoid'
Dynamoid.configure do |config|
# ...
end
In standalone Ruby applications, Dynamoid logs to $stdout and defaults config.namespace to 'dynamoid'.
Connection & Authentication
Dynamoid communicates with DynamoDB using the official AWS SDK for Ruby, which by default discovers credentials and region through the SDK’s configuration resolution chain by evaluating environment variables, AWS configuration profiles (~/.aws/credentials), or IAM roles.
To isolate Dynamoid from your global AWS configuration or connect to a local development emulator, you can configure connection parameters directly.
config.access_key and config.secret_key
- Default:
nil - Type:
String
Sets static AWS access key ID and secret access key strings directly on the Dynamoid client:
config.access_key = ENV['DYNAMODB_ACCESS_KEY_ID']
config.secret_key = ENV['DYNAMODB_SECRET_ACCESS_KEY']
Configuring these settings directly is helpful when your application uses static credentials specific to DynamoDB, without altering global AWS configuration. For dynamic, temporary, or role-based credentials, use config.credentials instead.
config.region
- Default:
nil - Type:
String
Specifies the AWS region hosting your DynamoDB tables (such as 'us-west-2' or 'eu-central-1'):
config.region = 'us-west-2'
When left as nil, the underlying AWS SDK attempts to resolve the region automatically from ENV['AWS_REGION'], ENV['AWS_DEFAULT_REGION'], or ~/.aws/config.
config.credentials
- Default:
nil - Type:
Aws::Credentialsor any object responding to#credentials
An object-based alternative to config.access_key and config.secret_key. While access_key and secret_key accept static string pairs, config.credentials accepts an AWS SDK credential provider object. This is typically used when authentication requires temporary session tokens, dynamic credential rotation, or AWS STS role assumption:
sts_client = Aws::STS::Client.new(region: 'us-west-2')
role_credentials = Aws::AssumeRoleCredentials.new(
client: sts_client,
role_arn: 'arn:aws:iam::123456789012:role/DynamoDBAppRole',
role_session_name: 'dynamoid-production'
)
config.credentials = role_credentials
For other supported credential classes, see the AWS SDK Credential Providers documentation.
When config.credentials is specified, it takes precedence and causes Dynamoid to ignore config.access_key and config.secret_key.
config.endpoint
- Default:
nil - Type:
String
Overrides the default AWS DynamoDB service URL. This setting is typically used during development and automated testing to direct database traffic to a local emulator, such as DynamoDB Local or LocalStack:
config.endpoint = 'http://localhost:8000'
When set to nil, requests are routed to the standard public AWS DynamoDB endpoint for the configured region.
HTTP Client
Dynamoid executes database requests through an underlying AWS SDK client. You can configure HTTP timeouts and proxies to control connection lifecycles and network routing.
These options are passed directly to Aws::DynamoDB::Client. When left as nil (the default), Dynamoid defers to the built-in defaults of the AWS SDK for Ruby.
config.http_open_timeout
- Default:
nil(AWS SDK default:15) - Type:
IntegerorFloat
The maximum number of seconds to wait when establishing a new TCP connection to DynamoDB before timing out:
config.http_open_timeout = 2
config.http_read_timeout
- Default:
nil(AWS SDK default:60) - Type:
IntegerorFloat
The maximum number of seconds to wait for a response from DynamoDB after sending a request before raising an HTTP read timeout exception:
config.http_read_timeout = 5
config.http_idle_timeout
- Default:
nil(AWS SDK default:5) - Type:
IntegerorFloat
The number of seconds a persistent connection can remain idle in the client connection pool before being closed and discarded:
config.http_idle_timeout = 10
Setting this to a higher value keeps connections alive longer, reducing SSL/TLS handshake overhead for background workers or high-throughput processes.
config.http_continue_timeout
- Default:
nil(AWS SDK default:1) - Type:
IntegerorFloat
The number of seconds to wait for an HTTP 100-continue response from DynamoDB before uploading the request payload:
config.http_continue_timeout = 1
config.http_proxy
- Default:
nil - Type:
StringorURI
A proxy URI string used to route all HTTP/HTTPS requests to DynamoDB:
config.http_proxy = 'http://proxy.corp.example.com:8080'
When set to nil, requests are dispatched directly, or follow standard proxy environment variables (HTTPS_PROXY or HTTP_PROXY) if configured in your environment.
Table Namespaces
Because DynamoDB table names are global within each AWS account and region, any two models that resolve to the same table name will target the same physical DynamoDB table.
Dynamoid allows configuring a namespace prefix to isolate tables across environments, applications, and test suites.
config.namespace
- Default:
"dynamoid_#{app_name}_#{Rails.env}"in Rails;'dynamoid'in standalone Ruby applications - Type:
Stringornil
Prepends a prefix to all model table names, joined by an underscore (for example, <namespace>_<table_name>):
config.namespace = 'myapp_production'
User.table_name # => "myapp_production_users"
To omit prefixes and use clean table names, set config.namespace to nil:
config.namespace = nil
User.table_name # => "users"
When multiple environments (e.g. staging and production) share an AWS account, include the environment name in config.namespace to prevent table collisions:
config.namespace = "myapp_#{ENV.fetch('APP_ENV', 'development')}"
When each environment runs in a dedicated AWS account, table name prefixes are redundant—setting config.namespace = nil keeps table names simple (users, orders).
When a test suite is split and run in parallel across multiple processes, include a process ID in config.namespace so each process uses its own tables:
worker_id = ENV['TEST_ENV_NUMBER'] || Process.pid
config.namespace = "myapp_test_#{worker_id}"
For model-level table name overrides and ARN mapping, see Table Mapping & Provisioning.
Throttling & Backoff Strategies
Dynamoid’s backoff mechanism controls retry delays during batch operations:
- Batch writes (
Model.import) — retries unprocessed items returned when a table exceeds its write capacity. - Batch reads (
Model.find([ids])) — retries unprocessed keys returned when a table exceeds its read capacity.
If none of the items in a batch can be processed, DynamoDB returns a throttling error, which the underlying AWS SDK automatically retries using its built-in backoff mechanism. However, when an operation is partially successful—processing some items while returning others as unprocessed—the SDK does not retry. In this scenario, Dynamoid retries the remaining items itself. Configuring config.backoff introduces delays between these retries to pace requests and prevent immediate tight loops that sustain table throttling.
By default, config.backoff is nil, meaning Dynamoid retries unprocessed batch items immediately without waiting between attempts.
config.backoff
- Default:
nil - Type:
Symbol,Hash, ornil
Selects the active backoff strategy and its parameters. Dynamoid provides two built-in strategies: :constant and :exponential.
Use :constant to pause for a fixed duration between retries (1 second by default):
config.backoff = :constant
Pass a hash to configure a custom delay in seconds:
config.backoff = { constant: 2 }
Use :exponential (truncated binary exponential backoff) to progressively double the wait time up to a ceiling (base_backoff: 0.5 seconds and ceiling: 3 by default):
config.backoff = :exponential
Pass a hash to customize base_backoff and ceiling:
config.backoff = { exponential: { base_backoff: 0.2, ceiling: 5 } }
During exponential backoff, the delay for retry attempt n is calculated as base_backoff * (2 ** [n - 1, ceiling - 1].min).
config.backoff_strategies
- Default:
{ constant: BackoffStrategies::ConstantBackoff, exponential: BackoffStrategies::ExponentialBackoff } - Type:
Hash{Symbol => #call}
A registry of available backoff algorithms. A strategy generator must be a callable object (such as a Proc or class implementing .call) that accepts optional configuration arguments and returns a callable object that executes the delay:
config.backoff_strategies[:jitter] = lambda do |max_seconds = 3|
-> { sleep(rand * max_seconds) }
end
Once registered, activate the custom strategy via config.backoff:
config.backoff = { jitter: 5 }
Table Provisioning
When Dynamoid creates DynamoDB tables, you can configure application-wide defaults for billing modes, throughput capacity, and synchronization timeouts. These settings provide fallbacks whenever a model does not specify them explicitly (see Table Settings).
config.create_table_on_save
- Default:
true - Type:
Boolean
When enabled (the default), saving a model instance automatically checks whether the physical DynamoDB table exists and creates it synchronously if missing.
While convenient for local development and testing, creating tables on the fly during normal write traffic introduces latency and risks table creation errors in multi-process production deployments. In production environments, disable auto-creation and provision tables upfront (see Table Creation and Management):
config.create_table_on_save = false
config.capacity_mode
- Default:
nil(DynamoDB defaults to:provisioned) - Type:
Symbolornil(:provisionedor:on_demand)
Sets the default billing mode for tables created by Dynamoid:
config.capacity_mode = :on_demand
When set to :on_demand, DynamoDB automatically accommodates workloads as they ramp up or down without specifying read or write capacity units.
config.read_capacity and config.write_capacity
- Default:
read_capacity = 100,write_capacity = 20 - Type:
Integer
Sets the baseline Read Capacity Units (RCU) and Write Capacity Units (WCU) allocated to newly created tables when operating in :provisioned mode:
config.read_capacity = 50
config.write_capacity = 10
These values can be overridden on individual models using the table method.
config.sync_retry_max_times and config.sync_retry_wait_seconds
- Default:
sync_retry_max_times = 60,sync_retry_wait_seconds = 2 - Type:
Integer
Controls polling behavior when creating tables synchronously (via create_table(sync: true) or when create_table_on_save is enabled).
Because DynamoDB table creation is asynchronous, Dynamoid polls table status until the table becomes active or the retry limit is reached:
config.sync_retry_wait_seconds = 1
config.sync_retry_max_times = 30
config.models_dir
- Default:
'./app/models' - Type:
String
Specifies the directory path where Dynamoid model files are stored:
config.models_dir = './lib/my_app/models'
The rake dynamoid:create_tables task scans this directory recursively to discover and load all model classes before provisioning tables.
For full details on table provisioning and index configuration, see Table Mapping & Provisioning.
Query & Scan Safeguards
In Amazon DynamoDB, a Query operation looks up items efficiently using an equality condition on a partition key (either on the table or a secondary index). When a query’s where conditions do not specify a partition key, DynamoDB falls back to a Scan operation, reading every item in the entire table.
On large tables, unexpected scans consume massive read capacity, incur unexpected AWS costs, and degrade application latency. Dynamoid provides configuration safeguards to detect and prevent accidental scans.
config.warn_on_scan
- Default:
true - Type:
Boolean
Logs a warning message whenever a query with where conditions falls back to a Scan operation:
config.warn_on_scan = true
When enabled, calling where without a partition key condition emits a warning:
WARN -- : Queries without an index are forced to use scan and are generally much slower than indexed queries!
WARN -- : You can index this query by adding index declaration to user.rb:
Note
warn_on_scantriggers only whenwhereconditions are present (such asUser.where(role: 'admin')). Explicit, unconditioned table scans such asUser.alldo not emit warnings.
config.error_on_scan
- Default:
false - Type:
Boolean
Raises an exception whenever a query with where conditions falls back to a Scan operation:
config.error_on_scan = true
Enabling error_on_scan in automated test suites and staging environments is recommended to catch accidental table scans before they reach production.
Like warn_on_scan, error_on_scan only raises when where conditions are present (such as User.where(...)); it does not prevent intentional full-table scans such as User.all.
For detailed querying patterns and index strategies, see Query Interface.
Storage & Field Defaults
These settings define application-wide defaults for field persistence, type casting, time zones, and serialization. Many of these global options can be overridden on individual model fields (for example, field :logged_at, :datetime, store_as_string: true).
config.timestamps
- Default:
true - Type:
Boolean
Controls whether Dynamoid automatically declares and manages created_at and updated_at datetime fields on all models:
config.timestamps = false
When set to false, timestamps are disabled globally unless enabled on individual models via table timestamps: true. For model-level overrides and automatic timestamp tracking, see Timestamps.
config.application_timezone and config.dynamodb_timezone
- Default:
:utcfor both - Type:
Symbol(:utc,:local) orString(e.g.,'America/New_York')
Controls how time zones are handled when loading and persisting datetime attributes.
config.application_timezone sets the time zone to which datetime attributes are converted when loaded into application memory. It accepts :utc (the default), :local (the host system’s time zone), or any named time zone string (such as 'America/New_York', or Time.zone.name in Rails):
config.application_timezone = 'America/New_York'
config.dynamodb_timezone defines the time zone used when persisting timestamps as ISO-8601 formatted strings in DynamoDB (when store_datetime_as_string is enabled):
config.dynamodb_timezone = :utc
config.store_datetime_as_string and config.store_date_as_string
- Default:
falsefor both - Type:
Boolean
Governs the DynamoDB wire format used for datetime and date attributes.
By default, datetime fields are stored as numeric seconds since epoch with nanosecond precision, and date fields are stored as integer days since epoch. When set to true, values are stored as ISO-8601 formatted strings ("YYYY-MM-DDTHH:MM:SSZ" and "YYYY-MM-DD"):
config.store_datetime_as_string = true
config.store_date_as_string = true
config.store_boolean_as_native
- Default:
true - Type:
Boolean
By default, booleans are stored as native DynamoDB boolean attributes. When set to false, they are stored as single-character strings ('t' or 'f') for backward compatibility with legacy tables:
config.store_boolean_as_native = false
config.store_binary_as_native
- Default:
false - Type:
Boolean
By default, binary data is stored as a Base64-encoded string. When set to true, binary fields persist as native DynamoDB binary attributes:
config.store_binary_as_native = true
config.store_empty_string_as_nil and config.store_attribute_with_nil_value
- Default:
store_empty_string_as_nil = true,store_attribute_with_nil_value = false - Type:
Boolean
Controls how empty strings and nil attributes are persisted in DynamoDB.
When config.store_empty_string_as_nil is true, empty strings ("") are converted to nil before saving (a default preserved for compatibility with early DynamoDB versions that prohibited empty strings). Set to false to store empty strings as regular strings:
config.store_empty_string_as_nil = false
When config.store_attribute_with_nil_value is false, attributes assigned nil are deleted from the DynamoDB item, saving storage space. When true, Dynamoid persists an explicit null value:
config.store_attribute_with_nil_value = true
config.convert_big_decimal
- Default:
false - Type:
Boolean
By default, numbers inside :map and :raw fields are loaded as BigDecimal instances. When config.convert_big_decimal is true, Dynamoid converts them to Float values instead.
config.convert_big_decimal = true
config.use_yaml_unsafe_load and config.yaml_permitted_classes
- Default:
use_yaml_unsafe_load = false(on Ruby >= 3.1),yaml_permitted_classes = [Symbol, Set, Date, Time, DateTime] - Type:
BooleanandArray<Class>
By default, Dynamoid deserializes :serialized fields safely using YAML.safe_load, allowing only the classes listed in yaml_permitted_classes. To permit additional classes, add them to config.yaml_permitted_classes:
config.yaml_permitted_classes += [CustomClass]
If you trust the stored data or need to deserialize arbitrary Ruby classes without maintaining an allowlist, set config.use_yaml_unsafe_load = true.
For more details, see YAML Deserialization.
Diagnostics & Logging
Dynamoid logs database operations, execution timings, and warnings. The configured logger is also forwarded directly to the underlying Aws::DynamoDB::Client. In Rails applications, Dynamoid defaults to Rails.logger. In standalone Ruby applications, it prints to $stdout.
config.logger
- Default:
Rails.loggerin Rails;Logger.new($stdout)in standalone Ruby applications - Type:
Loggerinstance,false, ornil
Sets the active logger:
config.logger = Logger.new('log/dynamoid.log')
To disable logging entirely (for example, in tests), pass false or nil:
config.logger = false
Set the logger’s level to Logger::DEBUG to output timing and argument details for every database operation:
config.logger.level = Logger::DEBUG
config.log_formatter
- Default:
nil - Type:
Aws::Log::Formatterornil
Customizes the log format used by the underlying AWS SDK client when logging HTTP request and response metadata:
config.log_formatter = Aws::Log::Formatter.colored
You can pass built-in formatters such as Aws::Log::Formatter.colored or Aws::Log::Formatter.short, define custom pattern strings with Aws::Log::Formatter.new(pattern), or provide any object responding to #format(response). For available patterns, see the AWS SDK Log Formatter documentation.
When left as nil, the AWS SDK uses its default format.
Identity Map
Dynamoid includes an implementation of Fowler’s Identity Map pattern, which ensures that each DynamoDB item is loaded into memory only once per context.
config.identity_map
- Default:
false - Type:
Boolean
When enabled, subsequent lookups for the same primary key return the existing in-memory model instance rather than issuing another request to DynamoDB:
config.identity_map = true
Because the identity map retains object references in memory, enabling it without request-scoped clearing causes memory leaks in long-running processes (such as Puma servers or background workers) and can serve stale attributes across separate web requests.
In Ruby on Rails applications, insert the Dynamoid::Middleware::IdentityMap middleware in config/application.rb to clear the map at the beginning and end of each HTTP request:
config.middleware.use Dynamoid::Middleware::IdentityMap
In other Rack applications, add the middleware in config.ru:
use Dynamoid::Middleware::IdentityMap
In background job processors (such as Sidekiq or GoodJob), reset the map between jobs:
Dynamoid::IdentityMap.clear
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.
Testing
Running automated tests with Dynamoid requires configuring a dedicated test environment—typically targeting a local emulator with an isolated table namespace—guarding against accidental changes to remote or non-test tables, and managing table lifecycles and item cleanup without database transactions.
Configuration
When running tests against a local emulator (such as DynamoDB Local or LocalStack), configure config.endpoint in your test setup (such as config/environments/test.rb, spec/support/dynamoid.rb, or test/test_helper.rb) to route requests to the local service instead of AWS:
Dynamoid.configure do |config|
config.endpoint = 'http://localhost:8000'
end
Because the AWS SDK requires a region and credentials even when connecting to a local emulator, configure dummy values if they are not already present in the environment (such as in CI containers):
config.region = 'us-west-2'
config.access_key = 'test'
config.secret_key = 'test'
To prevent test runs from overwriting or dropping development tables on the same emulator, configure a dedicated config.namespace for the test environment. When running tests in parallel across multiple processes, append an environment variable containing a unique worker identifier (such as ENV['TEST_ENV_NUMBER']) so each process operates on its own tables:
config.namespace = "myapp_test#{ENV['TEST_ENV_NUMBER']}"
Outside Rails (where Dynamoid uses Rails.logger), config.logger defaults to $stdout at Logger::INFO level, printing every database operation into the test output. To silence routine logs while keeping warnings and errors visible, raise the log level:
config.logger.level = Logger::WARN
Alternatively, redirect logs to a file or disable logging:
config.logger = Logger.new('log/test.log')
# or
config.logger = false
To catch accidental full-table scans during test runs before they reach production, enable config.error_on_scan so Dynamoid raises Dynamoid::Errors::ScanProhibited whenever where conditions trigger a Scan operation:
config.error_on_scan = true
Safety Guards
To prevent test runs from accidentally modifying or dropping development, staging, or production tables, add a guard in your test helper to verify that Dynamoid.config.namespace is set to a test namespace:
unless Dynamoid.config.namespace.to_s.include?('test')
raise "Refusing to run tests with non-test namespace: #{Dynamoid.config.namespace.inspect}"
end
When your test suite runs against a local emulator, also verify that Dynamoid.config.endpoint points to a local host rather than remote AWS:
host = URI(Dynamoid.config.endpoint.to_s).host
unless ['localhost', '127.0.0.1'].include?(host)
raise "Refusing to run tests against non-local endpoint: #{Dynamoid.config.endpoint.inspect}"
end
Test Suite Integration
Because DynamoDB does not support rollbackable transactions, test suites cannot isolate tests by rolling back database state; instead, use Dynamoid::TestHelper to provision tables and clear items between tests.
To provision missing tables once before the test suite starts (or only for specific models when running a subset of tests), call create_tables:
Dynamoid::TestHelper.create_tables
# or
Dynamoid::TestHelper.create_tables(User, Post)
If your models live outside ./app/models, configure config.models_dir to point to their directory—when called without arguments, create_tables only creates tables for models in that directory.
To clear stored items between individual tests while keeping the tables intact, call truncate_tables:
Dynamoid::TestHelper.truncate_tables
# or
Dynamoid::TestHelper.truncate_tables(User, Post)
Because create_tables skips tables that already exist, changing a model’s primary key or secondary indexes requires dropping existing tables first. To delete all tables in the configured config.namespace, call drop_tables:
Dynamoid::TestHelper.drop_tables
Running drop_tables before every test suite run guarantees a fresh schema, while omitting it (or gating it behind an environment variable) avoids recreating unchanged tables on every local test run.
RSpec
In projects using RSpec, configure table lifecycle hooks in spec/support/dynamoid.rb (or spec/spec_helper.rb):
RSpec.configure do |config|
config.before(:suite) do
Dynamoid::TestHelper.drop_tables
Dynamoid::TestHelper.create_tables
end
config.before(:each) do
Dynamoid::TestHelper.truncate_tables
end
end
Minitest
In projects using Minitest (or ActiveSupport::TestCase in Rails), add the equivalent lifecycle hooks to test/test_helper.rb:
Dynamoid::TestHelper.drop_tables
Dynamoid::TestHelper.create_tables
class Minitest::Test
def setup
super
Dynamoid::TestHelper.truncate_tables
end
end
# or in Rails:
class ActiveSupport::TestCase
setup do
Dynamoid::TestHelper.truncate_tables
end
end
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.