---
title: Data Sync
slug: v4-4/qa93Zj1Xd610ZXi8WT0Lt
docTags: 
createdAt: 2023-08-22T20:57:32.293Z
---

This article provides step-by-step instructions for setting up, maintaining, and ending data subscriptions for peer-to-peer asynchronous replication:

- [Creating Subscriptions](docId\:biHWAat_c2QuvWCja4H-h)
- [Managing Lifetime Subscriptions](./#managing-lifetime-subscriptions)
- [Canceling Subscriptions](./#canceling-subscriptions)

:::ExpandableHeading
### Learn the Basics of Subscriptions

Data *synchronization,&#x20;*&#x6F;r "sync" for short, refers broadly to the practice of ensuring that peers always have the most up-to-date and accurate information.&#x20;

However, data sync goes beyond basic updates and involves a *replication&#x20;*&#x70;rocess, along with other sophisticated techniques for ensuring data is up-to-date and consistent across the mesh network. Replication, in the most basic terms, refers to the process of copying and syncing data across multiple Small Peers; as in, the multiple storage locations that run locally within an end-user physical environment, such as a mobile device.&#x20;

To replicate data in Ditto, you establish a *subscription*. A subscription acts as a listener that, in conjunction with a *replication query*, specifies the specific remote events a Small Peer is interested in receiving data updates for. A replication query is essentially a request made by a peer to fetch data matching the query's criteria from other peers in order to sync. These replication queries define the criteria and conditions for the associated subscription.

For more information, see [Sync and Replication Concepts](docId\:Vh2a6OTl4DLnEl0A-mIU8) in "Advanced Concepts."&#x20;
:::

# Creating Subscriptions

To set up a replication subscription in your app:

:::hint{type="warning"}
Syncing large documents can significantly impact sync performance:

Be cautious handling very large binary data, a deeply embedded document, or a very large document. Carefully consider using `attachments` instead of storing the data directly within a document object. For more information, see [Attachment](docId\:yxemKH1COm3CSUuMqcnlf) and [Large Binary Files](docId\:AlJX_b0k4mimi68y7G0oh).
:::

::::WorkflowBlock
:::WorkflowBlockItem
Start data replication within your app's development lifecycle. ([Initiating Replication](./#initiating-replication))
:::

:::WorkflowBlockItem
Instantiate a top-level `subscription` object. ([Creating Subscriptions](./#creating-subscriptions))
:::

:::WorkflowBlockItem
If applicable, end the subscription. ([Canceling Subscriptions](./#canceling-subscriptions))
:::
::::

## Initiating Replication

Before you can set up your subscription listener, initiate the replication process in your app. Initiating replication indicates that you're ready receive updates from remote peers, as well as send updates to subscribing remote peers.

To initiate replication, early in your app lifecycle, such as within `AppDelegate.application(_:didFinishLaunchingWithOptions:)` or `Application.onCreate` methods, call the `startSync` method.

:::hint{type="info"}
You only need to call the following function once.
:::

:::hint{type="danger"}
You must start replication (`startSync`) in the top-most scope to ensure that as soon as your app starts, it automatically connects with the mesh network and remains active throughout your app's lifecycle.

Otherwise, the peer-to-peer connection may fail, resulting in remote peers becoming unable to send you updates in realtime.
:::

:::CodeblockTabs
```swift
try! ditto.startSync()
```

```kotlin
try {
    ditto.startSync()
} catch (e: DittoError) {
    // handle error
}
```

```javascript
try {
  ditto.startSync()
} catch (err) {
  console.error(err)
}
```

```java
try {
    ditto.startSync();
} catch(DittoError e) {
    // handle error
}
```

```csharp
try
{
    ditto.StartSync();
}
catch (DittoException ex)
{
    // handle exception
}
```

```cpp
try {
  ditto.start_sync();
} catch (const DittoError &err) {
  std::cerr << err.what();
}
```

```rust
ditto.try_start_sync()?;
```
:::

## Creating Subscriptions

In the top-most scope of your app, following the `startSync` method called in the previous step, set up a `subscription` object:

:::hint{type="warning"}
You must declare your subscription object from the top-most scope of your app to ensure access throughout your app.&#x20;

Otherwise, you cannot modify or cancel your subscription from any part of your code, resulting in difficulty and potential errors when managing the subscription's lifecycle.
:::

1. Pass your replication query as an argument to find.&#x20;

2. Call the Subscribe method, and then pass the subsequent actions and processes you want to execute when your criteria are met as an argument. &#x20;

Once you've set up your subscription, your subscription query is automatically sent to all peers connected to the mesh network. If there are any data changes that match your criteria, Ditto automatically triggers your `subscribe` callback function that performs followup actions and processes in your app.

:::CodeblockTabs
```swift
let subscription = ditto.store
    .collection("your_collection_name")
    .find(query)
    .subscribe()
```

```kotlin
val subscription = ditto.store
    .collection("your_collection_name")
    .find(query)
    .subscribe()
```

```javascript
const subscription = ditto.store
  .collection("your_collection_name")
  .find([query])
  .subscribe()
```

```csharp
const subscription = ditto.Store
  .Collection("your_collection_name")
  .Find([query])
  .Subscribe()
```

```cpp
std::shared_ptr<ditto::Subscription> subscription = ditto.get_store()
  .collection("your_collection_name")
  .find([query])
  .subscribe();
```

```rust
let collection = ditto.store()
  .collection("your_collection_name").unwrap();

const subscription = collection
  .find([query])
  .subscribe();
```
:::

For example, the following snippet demonstrates how to establish a `carsSubscription` to listen for all updates to documents in the `"cars"` collection with a field of `color` set to the value `"blue"`:

:::CodeblockTabs
```swift
let carsSubscription = ditto.store
  .collection("cars")
  .find("color == 'blue'")
  .subscribe()
```

```kotlin
val carsSubscription = ditto.store.collection("cars")
    .find("color == 'blue'")
    .subscribe()
```

```javascript
const subscription = ditto.store
  .collection("cars")
  .find("color == 'blue'")
  .subscribe()
```

```java
```

```csharp
var subscription = ditto.store
  .Collection("cars")
  .Find("color == 'blue'")
  .Subscribe()
```

```cpp
std::shared_ptr<ditto::Subscription> subscription = ditto.get_store()
  .collection("cars")
  .find("color == 'blue'")
  .subscribe();
```

```rust
const subscription = ditto.store
  .collection("cars")
  .find("color == 'blue'")
  .subscribe();
```
:::

# Managing Lifetime Subscriptions

In order to prevent memory leaks, Ditto's built-in memory management mechanisms automatically cancels active subscriptions that are no longer needed or relevant.

Therefore, if you store the subscription object at a local scope within your code, once Ditto executes your `subscribe` callback function, the subscription object may be removed from memory leading to unexpected behaviors.&#x20;

# Canceling Subscriptions

To cancel a subscription, call `cancel` on the subscription object you set up to establish your subscription:

:::CodeblockTabs
```swift
subscription.cancel()
```

```kotlin
subscription.cancel()
```

```javascript
subscription.cancel();
```

```java
```

```csharp
subscription.Cancel();
```

```cpp
subscription.cancel();
```

```rust
subscription.cancel();
```
:::

For example, continuing with the previous example, the following snippet illustrates canceling the `carsSubscription`:

:::CodeblockTabs
```swift
carsSubscription.cancel()
```

```kotlin
carsSubscription.cancel()
```

```javascript
carsSubscription.cancel();
```

```java
```

```csharp
carsSubscription.Cancel();
```

```cpp
std::shared_ptr<ditto::Subscription> carsSubscription = ditto.get_store()
  .collection("cars")
  .find("color == 'blue'")
  .subscribe();
  
carsSubscription.cancel();
```

```rust
carsSubscription.cancel();
```
:::

