Search code examples
microsoft-graph-apimicrosoft-graph-mail

Best practice for syncing mailbox state, Deltas vs. Subscriptions


I am building a CRM which handles email exchange in the app by processing emails sent to the Office365 accounts of the users using Microsoft Graph API. What is the best practice to keep track of emails in the actual mailbox? Should I use delta's or subscriptions?

From what I can tell, Delta's are URLs which give data about the current state of the mailbox, but deltas need to be triggered on a regular basis (I'd use a CRON job) but then I'd be running the process a lot more than needed because users don't receive that many emails per day.

Alternatively if I use a subscriptions that will let me know when a new email is received and I can process using a webhook in my app.

From the Microsoft Graph documentation it seems like deltas are the way to keep track of changes, but I feel like since all I need is to know when a new email is received so that it can be processed accordingly, delta's would be overkill in a sense.


Solution

  • You use a combination of the two.

    The webhook tells you the mailbox has changed, the delta tells what has changed in the mailbox. When you receive a notification, you pull the delta to retrieve the changes to the mailbox.

    There are many reasons for doing this, but the primary one is that the id of an email can change. This is because Message IDs are a composite value that includes the folder it is stored in. So if the message gets moved, the Id you received in the notification will be invalid. Historically this was a somewhat rare race condition, but with the advent of interactive mobile notifications, it is now commonplace for an email to come in and instantly get "archived". By relying on webhooks for notifications and deltas for content, you avoid a CRON job while mitigating the Id changing before you can process the message.