# Store user metadata (/en/realtime-media/rtm/build/manage-presence-and-metadata/storage/store-user-metadata/windows)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

The Signaling storage service enables you to store and share contextual user data in your app, such as name, date-of-birth, avatar, and connections. When user metadata is set, updated, or deleted, the SDK triggers a storage event notification. Other users in the channel receive this notification within 100ms and use the information according to your business logic.

    ## Understand the tech [#understand-the-tech-5]

    Use metadata enables you to store and share user level information. A set of user metadata facilitates business-level data storage and real-time notifications. Each user has only one set of user metadata, but each set may contain multiple metadata items. For relevant restrictions, refer to the [API usage restrictions](../../../reference/limitations). Each metadata item has `key`, `value`, and `revision` properties.

    User metadata is stored permanently in the Signaling database. The data persists even after a user logs out. You must explicitly delete it to remove it from the database. This feature impacts your storage billing. Refer to [Pricing](../../../reference/pricing) for details.

    ## Prerequisites [#prerequisites-5]

    Ensure that you have:

    * Integrated the Signaling SDK in your project .
    * Implemented the framework functionality from the [SDK quickstart](../../../quickstart) page.
    * Enabled storage in [Storage configuration](../../../manage-agora-account#storage-configuration).

    ## Implement user metadata storage [#implement-user-metadata-storage-5]

    The section shows you to implement user metadata storage in your Signaling app.

    ### Set user metadata [#set-user-metadata-5]

    To create a new metadata item for the user, or to update the `value` of am existing item, call `setUserMetadata`. This method creates a new item in the user metadata if the specified `key` does not exist, or overwrites the associated `value` if a metadata item with the specified `key` already exists.

    The following example saves a set of metadata items for a specified user. It configures the `options` parameter to add timestamp and modifier information to each metadata item.

    ```cpp
    Metadata metadata;
    std::vector<agora::rtm::MetadataItem> items;
    items.emplace_back(MetadataItem("Name", "Tony"));
    items.emplace_back(MetadataItem("Age", "40"));
    items.emplace_back(MetadataItem("Avatar", "https://your-domain/avatar/tong.png"));
    metadata.items = items.data();
    metadata.items = items.size();

    MetadataOptions options;
    options.recordTs = true;
    options.recordUserId = true;

    uint64_t requestId;
    rtm_client->getStorage()->setUserMetadata("Tony", metadata, options, requestId);
    ```

    After you call this method, the SDK triggers the `onSetUserMetadataResult` callback to return the call result.

    ```cpp
    // Asynchronous callback
    class RtmEventHandler : public IRtmEventHandler {
        void onSetUserMetadataResult(const uint64_t requestId, const char *userId, RTM_ERROR_CODE errorCode) override {
            if (errorCode != RTM_ERROR_OK) {
                printf("SetUserMetadata failed error is %d reason is %s\n", errorCode, getErrorReason(errorCode));
            } else {
                printf("SetUserMetadata success\n");
            }
        }
    };
    ```

    Additionally, Signaling triggers an `onStorageEvent` notification of event type `RTM_STORAGE_EVENT_TYPE_UPDATE` within 100 ms to inform all users who have subscribed to the this user's metadata.

    ### Get user metadata [#get-user-metadata-5]

    To retrieve all metadata items associated with a specific user, call `getUserMetadata`. Refer to the following example:

    ```cpp
    uint64_t requestId;
    rtmClient->getStorage()->getUserMetadata("Tony", requestId);
    ```

    After you call this method, the SDK triggers the `onGetUserMetadataResult` callback to return the call result.

    ```cpp
    // Asynchronous callback
    class RtmEventHandler : public IRtmEventHandler {
        void onGetUserMetadataResult(const uint64_t requestId, const char *userId, const Metadata& data, RTM_ERROR_CODE errorCode) override {
            if (errorCode != RTM_ERROR_OK) {
                printf("GetUserMetadata failed error is %d reason is %s\n", errorCode, getErrorReason(errorCode));
            } else {
                printf("GetUserMetadata success user id: %s\n", userId);
                for (int i = 0 ; i < data.itemCount; i++) {
                    printf("key: %s value: %s revision: %lld\n", data.items[i].key, data.items[i].value, data.items[i].revision);
                }
            }
        }
    };
    ```

    You can also leave the `userId` parameter blank to get the local user's metadata:

    ```cpp
    uint64_t requestId;
    rtmClient->getStorage()->getUserMetadata("userId", requestId);
    ```

    Signaling SDK returns the following data structure:

    ```js
    {
        majorRevision: 734874892,
        metadata:{
            "Name":{
                value:"Tony",
                revision:734874872,
                updated:1688978391900,
                authorUid:"Tony"
            },
            "Age":{
                value:"40",
                revision:734874862,
                updated:1688978390900,
                authorUid:"Tony"
            },
            "Avatar":{
                value:"https://your-domain/avatar/tong.png",
                revision:734874812,
                updated:1688978382900,
                authorUid:"Tony"
            }
        }
    }
    ```

    ### Update user metadata [#update-user-metadata-5]

    To modify existing metadata items, call `updateUserMetadata`. If the metadata item does not exist, the SDK returns an error. This method is useful for business use-cases that require permission control on creating new metadata items. For example, the admin defines the user metadata fields and users may only update the values.

    The following example updates the value of an existing metadata item:

    ```cpp
    Metadata metadata;
    std::vector<MetadataItem> items;
    items.emplace_back(MetadataItem("Age", "45"));
    metadata.items = items.data();
    metadata.itemCount = items.size();

    MetadataOptions options;
    options.recordTs = true;
    options.recordUserId = true;

    uint64_t requestId;
    rtmClient->getStorage()->updateUserMetadata("Tony", metadata, options, requestId);
    ```

    After you call this method, the SDK triggers the `onUpdateUserMetadataResult` callback to return the call result.

    ```cpp
    // Asynchronous callback
    class RtmEventHandler : public IRtmEventHandler {
        void onUpdateUserMetadataResult(const uint64_t requestId, const char *userId, RTM_ERROR_CODE errorCode) override {
            if (errorCode != RTM_ERROR_OK) {
                printf("UpdateUserMetadata failed error is %d reason is %s\n", errorCode, getErrorReason(errorCode));
            } else {
                printf("UpdateUserMetadata success\n");
            }
        }
    };
    ```

    Additionally, Signaling triggers an `onStorageEvent` notification of event type `RTM_STORAGE_EVENT_TYPE_UPDATE` within 100 ms to inform all users who have subscribed to the this user's metadata.

    ### Delete user metadata [#delete-user-metadata-5]

    To delete metadata items that are no longer required, call `removeUserMetadata`. Refer to the following sample code:

    ```cpp
    Metadata metadata;
    std::vector<MetadataItem> items;
    MetadataItem item;
    item.key = "Age";
    items.emplace_back(item);
    metadata.items = items.data();
    metadata.itemCount = items.size();

    uint64_t requestId;
    rtmClient->getStorage()->removeUserMetadata("Tony", metadata, MetadataOptions(), requestId);
    ```

    Setting the `value` for a metadata item that is being deleted has no effect.

    After you call this method, the SDK triggers the `onRemoveUserMetadataResult` callback to return the call result.

    ```cpp
    // Asynchronous callback
    class RtmEventHandler : public IRtmEventHandler {
        void onRemoveUserMetadataResult(const uint64_t requestId, const char *userId, RTM_ERROR_CODE errorCode) override {
            if (errorCode != RTM_ERROR_OK) {
                printf("RemoveUserMetadata failed error is %d reason is %s\n", errorCode, getErrorReason(errorCode));
            } else {
                printf("RemoveUserMetadata success\n");
            }
        }
    };
    ```

    Additionally, Signaling triggers an `onStorageEvent` notification of event type `RTM_STORAGE_EVENT_TYPE_UPDATE` within 100 ms to inform all users who have subscribed to the this user's metadata.

    To delete the entire set of metadata for a user, do not add any metadata items when calling `removeUserMetadata`. Refer to the following sample code:

    ```cpp
    Metadata metadata;
    MetadataOptions options;

    uint64_t requestId;
    rtmClient->getStorage()->removeUserMetadata("Tony", metadata, options, requestId);
    ```

    <CalloutContainer type="info">
      <CalloutDescription>
        When terminating a user account, it is common to delete the entire set of user's metadata. Once user metadata is deleted, it cannot be recovered. If you need data restoration, back up the metadata before deleting it.
      </CalloutDescription>
    </CalloutContainer>

    ## Receive storage event notifications [#receive-storage-event-notifications-5]

    A storage event notification returns the [StorageEvent](/en/api-reference/api-ref/signaling#configstorageeventpropsag_platform) data structure, which includes the [RTM\_STORAGE\_EVENT\_TYPE](/en/api-reference/api-ref/signaling#enumvstorageeventtypepropsag_platform) parameter.

    To receive storage event notifications, implement an event listener. See [event listeners](/en/api-reference/api-ref/signaling#event-listeners) for details. You only receive user metadata update notifications for users that you have subscribed to.

    #### Event notification mode [#event-notification-mode-5]

    Currently, Signaling only supports the full data update mode. This means that when a user's metadata is updated, the `data` field in the event notification contains all the metadata of the user.

    ### Subscribe to a user's metadata [#subscribe-to-a-users-metadata-5]

    To monitor updates to a user's metadata, you subscribe to their metadata. Refer to the following sample code:

    ```cpp
    uint64_t requestId;
    rtmClient->getStorage()->subscribeUserMetadata("Tony", requestId);
    ```

    After you call this method, the SDK triggers the `onSubscribeUserMetadataResult` callback to return the call result.

    ```cpp
    // Asynchronous callback
    class RtmEventHandler : public IRtmEventHandler {
        void onSubscribeUserMetadataResult(const uint64_t requestId, const char *userId, RTM_ERROR_CODE errorCode) override {
            if (errorCode != RTM_ERROR_OK) {
                printf("SubscribeUserMetadata failed error is %d reason is %s\n", errorCode, getErrorReason(errorCode));
            } else {
                printf("SubscribeUserMetadata success\n");
            }
        }
    };
    ```

    When there are changes in the user metadata, Signaling triggers an `onStorageEvent` notification of event type `RTM_STORAGE_EVENT_TYPE_UPDATE` within 100 ms to inform all users who have subscribed to this user's metadata.

    ### Unsubscribe from a user's metadata [#unsubscribe-from-a-users-metadata-5]

    When you no longer need to receive notifications about a user's metadata updates, unsubscribe from the users's metadata. Refer to the following sample code:

    ```cpp
    uint64_t requestId;
    rtm_client->getStorage()->unsubscribeUserMetadata("Tony", requestId);
    ```

    After you call this method, the SDK triggers the `onUnsubscribeUserMetadataResult`  callback to return the API call result.

    ```cpp
    // Asynchronous callback
    class RtmEventHandler : public IRtmEventHandler {
        void onUnsubscribeUserMetadataResult(const uint64_t requestId, const char* userId, RTM_ERROR_CODE errorCode) override {
            if (errorCode != RTM_ERROR_OK) {
                printf("UnsubscribeUserMetadata failed error is %d reason is %s\n", errorCode, getErrorReason(errorCode));
            } else {
                printf("UnsubscribeUserMetadata success\n");
            }
        }
    };
    ```

    ## Version control [#version-control-5]

    Signaling integrates compare-and-set (CAS) version control to manage metadata updates. CAS is a concurrency control mechanism to ensure that updates to a shared resource occur only if the resource is in an expected state. The mechanism works as follows:

    1. The client reads the current version of a data item.
    2. Before making an update, the client compares the current version with the last read version number.
    3. If the versions match, the client proceeds with the update and increments the version number. If they do not match, the update is aborted.

    CAS version control is useful in use-cases that require concurrency management. For instance, consider a dating application where only one user may engage in a chat session with a host. When multiple users attempt to join, only the first request is successful.

    The CAS version control feature provides two independent version control parameters. Set one or more of these values according to the needs of your business use-case:

    * `majorRevision` parameter in the `setMajorRevision` method: Enable version number verification of the entire set of user metadata.

    * `revision` parameter of a `MetadataItem`: Enable version number verification of a single metadata item.

    When setting user metadata, or a single user metadata item, use the revision attribute to enable or disable version control as follows:

    * To disable CAS verification, use the default value of `-1` for the `revision` parameter.

    * To enable CAS verification, set the `majorRevision` or the `revision` parameter to a positive integer. The SDK updates the corresponding value after successfully verifying the revision number. If the specified revision number does not match the latest revision number in the database, the SDK returns an error.

    The following code snippet demonstrates how to employ `majorRevision` and `revision` for updating user metadata and metadata items:

    ```cpp
    Metadata metadata;
    metadata.majorRevision = 734874892;
    std::vector<MetadataItem> items;
    items.emplace_back(MetadataItem("Avatar", "https://your-domain/avatar/tony.png", 734874812));
    metadata.items = items.data();
    metadata.itemCount = items.size();

    MetadataOptions options;
    options.recordTs = true;
    options.recordUserId = true;

    uint64_t requestId;
    rtmClient->getStorage()->updateUserMetadata("Tony", metadata, options, requestId);
    ```

    In this example, CAS verification for user metadata and metadata items is enabled by setting `majorRevision` and `revision` parameters to positive integers. Upon receiving the update call request, Signaling first verifies the provided major revision number against the latest value in the database. If there's a mismatch, it returns an error; if the values match, Signaling verifies the `revision` number for each metadata item using a similar logic.

    <CalloutContainer type="info">
      <CalloutDescription>
        When using version control, monitor `onStorageEvent` notifications to retrieve updated values for `majorRevision` and `revision` to ensure that the latest revision values are used for subsequent operations.
      </CalloutDescription>
    </CalloutContainer>

    ## Reference [#reference-5]

    This section contains content that completes the information on this page, or points you to documentation that explains other aspects to this product.

    ### API reference [#api-reference-5]

    * [`setUserMetaData`](/en/api-reference/api-ref/signaling#storagesetuserpropsag_platform)

    * [`getUserMetadata`](/en/api-reference/api-ref/signaling#storagegetuserpropsag_platform)

    * [`removeUserMetadata`](/en/api-reference/api-ref/signaling#storageremoveuserpropsag_platform)

    * [`updateUserMetadata`](/en/api-reference/api-ref/signaling#storageupdateuserpropsag_platform)

    * [`subscribeUserMetadata`](/en/api-reference/api-ref/signaling#storagesubscribeuserpropsag_platform)

    * [`unsubscribeUserMetadata`](/en/api-reference/api-ref/signaling#storageunsubscribeuserpropsag_platform)

    * [Metadata](/en/api-reference/api-ref/signaling#storagemetadatapropsag_platform)

    * [Event listeners](/en/api-reference/api-ref/signaling#event-listeners)

    
  
      
  
      
  
