Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions doc/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,18 +207,20 @@ config.namespace = nil
User.table_name # => "users"
```

How you configure `config.namespace` depends on your AWS account architecture:

* *Shared AWS accounts* — when development, test, and staging environments share an AWS account, dynamic namespaces prevent data collisions:
```ruby
config.namespace = "myapp_#{ENV.fetch('APP_ENV', 'development')}"
```
* *Dedicated AWS accounts* — when production and staging run in separate AWS accounts (the recommended AWS security architecture), table name prefixes are redundant. Setting `config.namespace = nil` keeps table names simple (`users`, `orders`).
* *Parallel test runners* — when executing tests concurrently across multiple workers (such as `parallel_tests` or multiple CI containers), incorporate the process or worker ID to isolate tables:
```ruby
worker_id = ENV['TEST_ENV_NUMBER'] || Process.pid
config.namespace = "myapp_test_#{worker_id}"
```
When multiple environments (e.g. staging and production) share an AWS account, include the environment name in `config.namespace` to prevent table collisions:

```ruby
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:

```ruby
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](modeling_and_schema/table_mapping_and_provisioning.md).

Expand Down
37 changes: 17 additions & 20 deletions doc/getting_started.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ DynamoDB stores data in *tables*, which contain *items* (analogous to rows or do

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.

The primary key is composed of one or two attributes:

* A *simple primary key* consists of a single attribute serving as the *partition key* (historically called a *hash key*). The value of this attribute must be unique across the entire table.
* A *composite primary key* is composed of two attributes: a *partition key* attribute and a *sort key* attribute (historically called a *range key*). The combination of both values forms the unique item identifier—multiple items can share the same partition key value as long as their sort key values differ.
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 whenever a search does not specify a partition key.
* A *scan operation* reads every item in the table when no partition key is specified.

## Key Differences from Relational Databases

Expand All @@ -31,20 +28,20 @@ In PostgreSQL or MySQL, table schemas define every column and data type upfront.

Primary keys also behave differently during writes:

* DynamoDB does not provide auto-incrementing integer sequences (`SERIAL` or `AUTO_INCREMENT`). Dynamoid automatically generates UUIDs for string partition keys, but integer partition keys and sort keys must be assigned by the application.
* An item's primary key (both the partition key and sort key) is strictly immutable once written. Changing an item's primary key requires creating a new item and deleting the original.
* Every write, update, and delete operation must target an item by its exact primary key—there is no equivalent to SQL's `UPDATE ... WHERE` or `DELETE ... WHERE` to modify or remove multiple rows matching arbitrary attribute conditions in a single statement.
* 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 ... WHERE` or `DELETE ... 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*.
* To filter efficiently by other attributes, you must define a secondary index (where those attributes serve as the index key) and target that index explicitly by name.
* Results can only be sorted by the sort key defined on the table or index—there is no arbitrary `ORDER BY` on non-key attributes.
* Pagination is forward-only. Unlike relational databases that support numeric `OFFSET` to jump to arbitrary pages, DynamoDB only allows traversing results sequentially from one page to the next, with no backward pagination.
* There is no `GROUP BY` clause or database-level aggregation (`SUM`, `AVG`, `MIN`, `MAX`). Finding totals or summary metrics requires calculating them in application code or maintaining pre-computed counter attributes with atomic increments.
* Unlike relational databases that guarantee immediate read-after-write consistency, DynamoDB reads (point lookups and queries) are *eventually consistent* by default—a read right after a write might briefly return stale data. When up-to-date data is required, you can request a *strongly consistent read* to guarantee seeing the latest write.
* 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 BY` on non-key attributes.
* Result sets are traversed forward using cursors—there is no numeric `OFFSET` to skip a given number of items.
* There is no `GROUP BY` or 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

Expand All @@ -62,9 +59,9 @@ DynamoDB does not support interactive transactions or pessimistic locking. While

DynamoDB also enforces several hard operational limits:

* Items cannot exceed 400 KB in total size, including all attribute names and values combined. Larger payloads or file attachments should be offloaded to external storage.
* A single query or scan operation returns at most 1 MB of data before pausing, requiring pagination even if a requested item limit has not yet been met.
* Native batch writes and deletes are capped at 25 items per request, while batch reads and transactions are limited to 100 items.
* An item cannot exceed 400 KB in total size ([including attribute names and values](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CapacityUnitCalculations.html)).
* 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

Expand Down Expand Up @@ -126,11 +123,11 @@ If a DynamoDB item contains attributes not declared in your Ruby model, Dynamoid

### Conventions and Defaults

Dynamoid follows *convention over configuration*, so a conventional model only needs to declare its fields:
Dynamoid follows *convention over configuration*, so a model only needs to declare its fields:

* Table names are automatically derived from the pluralized class name (`User` → `users`), prefixed by any configured namespace (`config.namespace`).
* The primary key defaults to a partition key named `id` of type `string`. When saving a new model, Dynamoid assigns an auto-generated UUID string if no `id` is specified.
* Timestamps are maintained automatically: Dynamoid generates `created_at` and `updated_at` datetime fields on every model by default.
* Table names are derived from the pluralized class name (`User` → `users`) and prefixed with `config.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_at` and `updated_at` datetime 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](modeling_and_schema/table_mapping_and_provisioning.md).
Expand Down
10 changes: 5 additions & 5 deletions doc/modeling_and_schema/associations.md
Original file line number Diff line number Diff line change
Expand Up @@ -751,8 +751,8 @@ Instead of querying a secondary index by foreign key, Dynamoid caches the partit

This storage strategy involves two deliberate simplifications:

* *Sets for all associations* — to keep the implementation uniform across all macros, Dynamoid uses a `<association>_ids` set attribute even for `has_one` and `belongs_to` associations, where the set holds only a single partition key.
* *Simple primary keys only* — because DynamoDB sets can only store scalar values, cached IDs only store partition keys. Models with composite primary keys (partition key and sort key) cannot declare or participate in associations.
* *Sets for all associations* — `has_one` and `belongs_to` also use an `<association>_ids` set 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:

Expand All @@ -772,9 +772,9 @@ 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 distinct trade-offs:
Relying on cached IDs rather than secondary indexes creates two trade-offs:

* *Item size growth* — every linked model adds an ID to the parent item's `<association>_ids` set. For high-cardinality relationships, this expands the item's payload, consumes more read and write capacity, and can eventually hit DynamoDB's hard 400 KB item size limit.
* *Outdated cached IDs* — because references are maintained entirely by Dynamoid in application code, deleting an item outside Dynamoid (or via class-level `Model.delete(id)`) leaves stale, orphaned IDs in the associated model's cached set.
* *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`, or `delete_all`) or outside Dynamoid does not update the associated model's cached ID set.

{{#include ../_includes/feedback.md}}
44 changes: 20 additions & 24 deletions doc/modeling_and_schema/fields_and_data_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -696,10 +696,10 @@ Dynamoid tracks changes in custom type attributes to determine which fields to u

To detect these changes, Dynamoid supports two comparison strategies:

* *Serialized comparison (default)* — Dynamoid serializes the attribute value and compares the serialized result against the database state. This works out of the box without requiring the custom type to implement `#==`. The trade-off is performance: serializing values whenever checking for changes (such as calling `changed?` or saving) incurs extra overhead.
* *In-memory comparison* — Dynamoid compares the Ruby objects directly in memory using `#==`, skipping serialization entirely.
* *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 `#==`.

To enable in-memory comparison, pass `comparable: true` in the field declaration:
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:

```ruby
class Order
Expand Down Expand Up @@ -845,20 +845,21 @@ The following table catalogs all configuration options that govern attribute ser

### 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:
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.

* *The Original 2012 Data Model* — DynamoDB launched supporting only strings and numbers, with binary data added later that year. It 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`.
* *Document Types & Null Values (October 2014)* — AWS introduced native booleans, explicit nulls, lists, and maps. Dynamoid introduced `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.
* *Empty String Support (May 2020)* — DynamoDB originally rejected empty strings, so Dynamoid automatically converted empty strings to `nil`. After DynamoDB added support for empty strings in 2020, Dynamoid introduced `store_empty_string_as_nil` (defaulting to `true` for backward compatibility) to allow applications to persist empty strings as-is.
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 `NULL` attributes provides two advantages:
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.

* *Storage and throughput efficiency* — In DynamoDB, attribute names and values both contribute to item size. Storing explicit `NULL` values increases item size and consumes additional read and write throughput, whereas omitting `nil` attributes conserves capacity.
* *Index compatibility and sparse indexes* — DynamoDB index keys (partition keys and sort keys for tables and secondary indexes) only support String, Number, or Binary types; they strictly prohibit `NULL`. Persisting an explicit `NULL` to an indexed attribute causes DynamoDB to raise a `ValidationException`. Omitting `nil` attributes prevents this error automatically and enables sparse secondary indexes.
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`:

Expand Down Expand Up @@ -893,33 +894,28 @@ user.reload.settings

### Time Zones

For `:datetime` fields, Dynamoid is time zone-aware and separates the time zone used in your application from the time zone used for database storage:

* `Dynamoid.config.application_timezone` (default `:utc`) — controls how `DateTime` instances are presented in your application (`:utc`, `:local`, or a named zone like `"America/New_York"`). In Rails applications, set this to `:local` or `Time.zone.name`.
* `Dynamoid.config.dynamodb_timezone` (default `:utc`) — controls the time zone used when writing timestamps to DynamoDB as ISO-8601 strings.

Strings without an explicit time zone offset are interpreted in `application_timezone`, normalized to `dynamodb_timezone` when stored, and converted back to `application_timezone` when loaded:
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`](../configuration.md#configapplication_timezone-and-configdynamodb_timezone):

```ruby
Dynamoid.configure do |config|
config.application_timezone = 'America/New_York'
config.dynamodb_timezone = :utc
config.store_datetime_as_string = true
end
```

order = Order.create!(placed_at: '2026-10-15 16:00:00')
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.placed_at
# => 2026-10-15T16:00:00-04:00
```ruby
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" (normalized to UTC)

order.reload.placed_at
# => 2026-10-15T16:00:00-04:00
# "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. (Numeric timestamps are stored as epoch seconds and are inherently UTC.)
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

Expand Down
Loading
Loading