title: How to enforce global uniqueness in a User table in CosmosDB
body: <p>I need to create a <code>User</code> table that at minimum looks like this:</p>
  
  <pre><code>public class User
  {
    public Guid Id {get; set;}
    public string Username {get; set;}
    public string EmailAddress {get; set;}
    public DateTime CreatedOn {get; set;}
  }
  </code></pre>
  
  <p>I'm currently writing all data to <code>CosmosDB</code> (SQL API). The problem is I need to add a unique index policy to <code>Username</code> and <code>EmailAddress</code> across all users. Since <code>CosmosDB</code> is designed with scaling out in mind, I'd need to partition this container. If I do so, I cannot enforce uniqueness across partitions. </p>
  
  <p>Currently, my partition key is <code>Id</code>. If I change my partition key to <code>Username</code> or <code>EmailAddress</code>, I fear that changing these fields can potentially result in users being deleted (e.g. delete old username and insert new username would be two separate transactions if the usernames belong to different partitions, which means there is no atomicity.).</p>
  
  <p>Is there a <code>CosmosDB</code> solution to this problem that I cannot think of? I can move this part to <code>SQL Server</code>, but I'll end up maintaining a large table over time. Also, since I'm using <code>Azure Functions</code> for server processing, shipping with EF DLLs makes the app size unnecessarily large.</p>