How to debug failures in Platform Events?

Debugging failure in platform events is very important because at times the data we send will not reach the destination platform. If we don't have a robust debugging mechanism data will be lost and that should not happen at any cost.

Platform event is an excellent way to send information to third-party systems using very minimal or no code in Salesforce.

There are a lot of advantages to using platform events in Salesforce, however, there are a few pitfalls as well.

In this blog post, we are going to discuss about the pitfalls.

I am sure by now you are already aware of this, but just trying to give you a gist of how Platform Events work.

Whenever we insert a record into the platform event, data will be put onto the event bus and the third-party system will try to extract the information from the event bus using Comet-D protocol.

The data that we put onto the event bus will be available for up to 72 hours.

Now let me take a step back and discuss the pitfalls in platform events.

When we put the data onto the event bus, at times the data might not be delivered, at times there might be a failure and the third-party system might not receive the information. In such cases, how do we handle the failures?

Apex has given us a very convenient mechanism to handle the failures.

There are two interfaces that are available out of the box and the interfaces are EventPublishFailureCallback and EventPublishSuccessCallback.

EventPublishFailureCallback is going to have a method that we need to overwrite and the method name is going to be onFailure.

Likewise, EventPublishSuccessCallback is going to have a method that we need to overwrite and the method name is going to be onSuccess.

So, you need to create a class, you need to implement these two interfaces, and overwrite the methods that are onFailure and onSuccess respectively.

This way what happens is, in case of failure in publishing the data, automatically onFailure method will be invoked. There we can write the subsequent business logic to handle failures.

Similarly, if you want to perform any action when data is successfully published, then we need to do the method overriding for the onSuccess method.

Have a look at the below code to get a hang of how to implement these two methods.

public class ExplorePlatformEventsController implements 
                            EventPublishFailureCallback, 
                            EventPublishSuccessCallback {

    public void onFailure(eventbus.FailureResult result) {
        List < String > uuids = result.getEventUuids();

        // do something
    }

    public void onSuccess(eventbus.SuccessResult result) {
        List < String > uuids = result.getEventUuids();

        // do something
    }

}

Debug failures in Platform Events

In the above code getEventUuids() returns a list of EventUuid field values of each platform event, using these we can retry or save the failed entries.

Hope this was helpful!