# Why is event schema validation essential for maintaining reliable contract communication between event publishers and subscribers?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Event Schemas, Data Validation

Read it on the site: https://www.forcechallenges.com/interview-questions/why-is-event-schema-validation-essential-for-maintaining-reliable-contract-communication-between-event

## Answer

**Basics:** A platform event is defined by its fields, types, lengths and required flags. Subscribers rely on those fields existing and meaning the same thing. If a publisher changes a field type or drops a field, consumers can fail silently.

**How it works:**
1. Define the platform event in Setup with typed fields, and mark must-have fields as required.
2. On publish, Salesforce rejects events with missing required fields or wrong types, and the `SaveResult` reports the error.
3. External clients get the Avro schema from Pub/Sub API `GetSchema`. Every schema revision has a schema ID.
4. Subscribers decode with the schema that matches the event's ID.

**Advanced / deep dive:** Platform events do not support validation rules or before triggers, so business validation (such as an allowed status value) belongs in the publishing code, a shared publisher class, or a gateway. Compatibility rules for changes:
- Adding an optional field is usually safe.
- Removing, renaming or retyping a field is breaking.
- For breaking changes, create a new version of the event (for example `Order_Event_v2__e`) and run both until subscribers migrate.

Include standard helpers in the payload design: an event ID or the built-in `EventUuid` for de-duplication, a version number, a business key, and a correlation ID. Keep payloads small and put identifiers rather than whole records in the event, to reduce schema churn. Publish a schema catalog and contract tests so teams see changes before release.

**Code / config example:**
```apex
public static Boolean isValid(Order_Event__e e, Set<String> allowed) {
    return e.Order_Id__c != null
        && e.Version__c != null
        && allowed.contains(e.Status__c);
}
// Publish only valid events; log or route the rest to an error object
```

**Hidden gotchas & must-remember points:**
- Salesforce validates types and required fields, not business rules.
- Field deletion or changes can break external subscribers using a cached schema.
- Required fields on events cannot be satisfied later by a subscriber, because the publisher must supply them.
- Event definitions are metadata, so deploy them through your pipeline in step with subscriber changes.
- Text field lengths truncate or fail, so validate long values.
- The platform has no built-in schema registry beyond `GetSchema`.

**Best practice:** Treat event definitions as versioned public APIs with owners, a catalog and a deprecation process.

---
Source: ForceChallenges · last updated 2026-11-02
