---
title: Register
slug: v4-4/ogNAL-jaJNg_lIrAA6S2E
docTags: 
createdAt: 2023-10-05T15:09:43.650Z
---

To start building your mental model, think of a CRDT as a container holding two essential components: the actual data to store and some metadata that helps in resolving conflicts.

## Representing the Actual Data

The `register` type holds the actual data to be stored; each set of fields in a document or key‑value pair embedded in a `map` function as a single `register` object.&#x20;

For example, the following snippet consists of three separate `registers`:

| **Field Property** | **Value** | **CRDT**             |   |
| ------------------ | --------- | -------------------- | - |
| `name`             | `'Frank'` | `register`(`string`) |   |
| `age`              | `31`      | `register`(`number`) |   |
| `ownedCars`        | `0`       | `counter` (`number`) |   |

:::CodeblockTabs
```swift
let docID = try ditto.store["people"].upsert([
        "name": "Frank",
        "age": 31,
        "ownedCars": DittoCounter()
```

```kotlin
val docId = ditto.store["people"].upsert(mapOf(
    "name" to "Frank",
    "ownedCars" to DittoCounter()
))

ditto.store.collection("people").findById(docId).update { mutableDoc ->
    mutableDoc!!["ownedCars"].counter!!.increment(amount = 1.0)
}
```

```javascript
const docID = await ditto.store.collection('people').upsert({
  name: 'Frank',
  age: 31,
  ownedCars: 0,
})
```

```java
Map<String, Object> content = new HashMap<>();
content.put("name", "Frank");
content.put("ownedCars", new DittoCounter());
DittoDocumentId docId = ditto.store.collection("people").upsert(content);

ditto.store.collection("people").findById(docId).update(mutDoc -> {
    assertThat(mutDoc).isNotNull();
    DittoMutableCounter counter = mutDoc.get("ownedCars").getCounter();
    assertThat(counter).isNotNull();
    counter.increment(1);
});
```

```csharp
var content = new Dictionary<string, object>
{
    { "name", "Frank" },
    { "age", 31 },
    { "ownedCars",  new DittoCounter() }
};
```

```cpp
json person = json({{"name", "Frank"}, {"age", 31}, {"ownedCars", 0});
DocumentId doc_id = ditto.get_store().collection("people").upsert(person);
```

```rust
let doc_id = ditto.store.collection("people").upsert(
    hashmap! {
        "name" => "Frank",
        "age" => 31,
        "ownedCars" => 0,
    },
);
```
:::

Since each set of fields in a document and, if embedded within a `map`, each key-value pair acts as a single `register`, you can structure, organize, and manage your data more efficiently.&#x20;

You can encode simple data as well as highly complex datasets in a `register`:

- To encode simple data in a `registers`, use primitive JSON-compatible types, such as `string`, `boolean`, `number`, and so on.

- To encode more complex datasets in a `register`, use a combination of primitive types and `register` and `maps`.&#x20;

The following table provides an overview of the types you can use to store a single value in a `register`:

| **Data Type**  | **Corresponding Values**                                                                                                                       |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `array`        | An ordered list of values, where each value represents any primitive type, as well as nested collection types such as other `arrays` or `maps` |
| `boolean`      | `true` or `false`                                                                                                                              |
| `float`        | 64-bit Floating-Point                                                                                                                          |
| `map`          | Embedded document object                                                                                                                       |
| `null`         | Represents an absence of a value                                                                                                               |
| `int`          | Signed 64-bit integer                                                                                                                          |
| `string`       | UTF-8 encodable                                                                                                                                |
| `unsigned int` | Unsigned 64-bit integer                                                                                                                        |

## Merging with Last-Writer-Wins Semantics

Each `register` adheres to the *last-writer-wins* principle at merge, ensuring conflict-free replication and data consistency throughout the distributed system.&#x20;

With last-writer-wins merge semantics, when conflicting updates occur, the update made by the last writer *always* takes precedence and propagates across peers as the single source of truth — the definitive value.&#x20;

For example, one flight attendant updates a customer's seat number to `6` and another to seat `9`. When two conflicting versions merge, the edit with the highest timestamp wins.&#x20;

## Array

An extension to the `register` type, an `array` is an ordered collection of items represented using any primitive JSON‑compatible data type enclosed within square brackets (\[ ]). 

:::hint{type="warning"}
Avoid using `arrays` in Ditto.&#x20;

Due to potential merge conflicts when offline peers reconnect to the mesh and attempt to sync their updates, especially when multiple peers make concurrent updates to the same item within the `array`.
:::

### Limitations to Arrays

CRDT-based `arrays`, when compared to typical `arrays`, have certain strengths and limitations.

While CRDTs excel at managing unordered operations, maintaining a strict order is less efficient, which could potentially lead to data inconsistencies at merge.&#x20;

The reason for this is because, unlike traditional `arrays`, the multiple elements within a CRDT-based `array` function collectively as a single `register`, and, as previously explained in [Ditto Basics](docId\:rb3wd2jhEnojPw8XUIRFy), a `register` is effectively a container that holds multiple elements — the actual data and various metadata — just like regular `arrays`.&#x20;

In simple terms, imagine an `array`like a `string`. Much like a `string`, each element in a CRDT-based `array` plays a unique role in determining the final value that ultimately forms; just like the `string` characters that eventually form a word.

Similar to how you access elements in a typical `array`, you reference each individual element in a CRDT-based `array` (a `register`) by their index. If those indexes change while disconnected from the network, once network conditions improve, they may fail to merge due to concurrency conflicts, resulting in data inconsistencies.

Considering this, avoid using `arrays` in Ditto and opt for a `map` instead, which effectively functions as a set, more commonly known as an *associative array.*

### Using a Map Instead of an Array

When managing data that requires unique identifiers and relationships, instead of using an `array` to encode your data, use a `map` with unique string keys and object values instead.&#x20;

For example, instead of representing an `array` of cars, where each element represents a car:

```json
{
  "cars": [
    {"make": "Toyota", "model": "Camry", "year": 2022},
    {"make": "Honda", "model": "Civic", "year": 2021},
    {"make": "Ford", "model": "Mustang", "year": 2023}
  ]
}
```

Implement a `map` instead:

```json
{
  "cars": {
    "car1": {"make": "Toyota", "model": "Camry", "year": 2022},
    "car2": {"make": "Honda", "model": "Civic", "year": 2021},
    "car3": {"make": "Ford", "model": "Mustang", "year": 2023}
  }
}
```

