Sub topic 12
Custom metadata types, external objects, big objects and platform events
This chapter covers four custom entity types that are not ordinary custom objects. Each has its own API name suffix and its own limits. You will learn what each is for, how to read and write it, and how to choose between them.
It assumes you can create a custom object and fields in Object Manager. It also assumes you know the __c and __r suffixes and have written basic SOQL and Apex.
Why more than one kind of custom entity
A custom object (__c) is a database table that Salesforce hosts. It supports records, page layouts, triggers, sharing and reports. That fits most business data, but it is a poor fit in four cases:
- Configuration that should travel with your code, not be re-entered in each org.
- Data that lives in another system and should not be copied.
- Billions of rows that would exhaust storage and slow queries.
- Messages that announce something happened, with no need to keep a record.
Each of the four types in this chapter covers one of these cases.
| Type | Suffix | Data lives | Main purpose |
|---|---|---|---|
| Custom metadata type | `__mdt` | In Salesforce, as metadata | Deployable configuration |
| External object | `__x` | In another system | Read (and optionally write) outside data in place |
| Big object | `__b` | In Salesforce, in a special store | Very large, mostly append-only data |
| Platform event | `__e` | Not stored as queryable rows | Event messages between systems or components |
Custom metadata types
A custom metadata type defines the structure of a set of configuration records. Each record is itself metadata. That has three consequences:
- Records deploy between orgs with change sets, packages or Salesforce DX. Custom object records do not.
- Apex can read records without a SOQL query that counts against governor limits.
getInstance()andgetAll()are served from cache. - Records are managed in Setup. Users do not edit them in the normal record UI, and sharing rules do not apply to them.
Typical uses are feature flags, tax rates per region, endpoint URLs, and mapping tables used by code.
Suppose you created a type labeled Feature Flag. Its API name is Feature_Flag__mdt. It has a checkbox field Enabled__c, and a record whose developer name is New_Billing. The following Apex reads that record:
Feature_Flag__mdt flag = Feature_Flag__mdt.getInstance('New_Billing');
if (flag != null && flag.Enabled__c) {
System.debug('New billing flow is on');
} else {
System.debug('Using legacy billing');
}getInstance() takes the record's developer name and returns null if there is no match. Always check for null.
You can also query these types with SOQL, which is useful in the Developer Console or when you need a WHERE clause:
SELECT DeveloperName, Label, Enabled__c
FROM Feature_Flag__mdt
WHERE Enabled__c = trueGotchas
- Apex cannot insert or update custom metadata records with ordinary DML. To change them at run time you must use the Metadata API deployment classes, which is rarely worth it. If code needs to write values, use a custom object or a custom setting.
- Each record has a
DeveloperNameand aLabel. The developer name is the stable key for code. Do not use the label. - Fields on a custom metadata type can be marked protected in a managed package so that subscribers cannot read the values.
External objects
An external object (__x) is a table definition that points at data in another system. Salesforce Connect fetches rows on demand. Nothing is copied into Salesforce storage.
You set one up in three steps:
- Create an external data source. This specifies the connection type and the endpoint. Common types are OData 2.0, OData 4.0, the cross-org adapter (to read another Salesforce org), and a custom adapter written in Apex.
- Choose Validate and Sync to create external objects from the remote tables.
- Grant users access through permission sets, as for any other object.
Every external object has two standard fields:
ExternalIdholds the remote primary key.DisplayUrlholds a link to the record in the source system.
Salesforce creates a Name-like field mapped from your choice of remote column. Other fields are custom fields ending in __c, because the __x suffix applies to the object and the fields keep __c.
Relationships
External objects use their own relationship types:
- External lookup links an external object (child) to a standard or custom object (parent).
- Indirect lookup links a standard or custom object (child) to an external object (parent). The match uses a field you designate as the external ID on the parent.
- A normal lookup from an external object to another external object works when both come from the same data source.
Querying
SOQL works against external objects in the same way:
SELECT ExternalId, Name__c, Status__c
FROM Order__x
WHERE Status__c = 'Shipped'
LIMIT 20This assumes an external object Order__x with the custom fields shown.
Every query becomes a callout to the remote system. Expect these limits:
- Latency depends on the remote system, so reports and list views are slower.
- Callout limits per transaction and hourly limits apply to the data source.
- Some features are limited or unavailable. Several aggregate functions, formula fields on remote data, and some report types do not work, depending on the adapter.
Big objects
A big object (__b) stores very large volumes, typically hundreds of millions to billions of rows, on a separate platform store. Typical examples are audit trails, IoT readings, and historical transactions.
The trade-offs are significant:
- You define an index when you create the big object. The index is an ordered list of fields (up to five). It cannot be changed after creation, and you must decide it carefully.
- Index fields must be required.
- Queries must filter on the index fields in order, starting from the first. You can use equality on the leading fields and a range or equality on the last field you use. Skipping an index field is an error.
- No triggers, no flows, no standard page layouts, and no sharing rules on big objects. Access is through object permissions and field-level permissions.
- Records are not updated by ordinary DML. Writing with the same index values overwrites the earlier row (upsert behavior), and deletion uses a dedicated method.
Imagine Customer_Interaction__b with fields Account__c (lookup), Created_At__c (date/time), Type__c (text) and Notes__c (text), where the index is Account__c then Created_At__c. The index fields are marked required. This Apex writes a row:
Account acc = [SELECT Id FROM Account LIMIT 1];
Customer_Interaction__b row = new Customer_Interaction__b(
Account__c = acc.Id,
Created_At__c = System.now(),
Type__c = 'Call',
Notes__c = 'Asked about renewal'
);
Database.SaveResult result = Database.insertImmediate(row);
System.debug('Saved: ' + result.isSuccess());Database.insertImmediate() writes at once and cannot be rolled back, because big object writes are outside the normal transaction. Do not mix it into logic that expects an all-or-nothing outcome.
A query that follows the index:
SELECT Account__c, Created_At__c, Type__c
FROM Customer_Interaction__b
WHERE Account__c = '001000000000001AAA'
AND Created_At__c >= 2026-01-01T00:00:00ZReplace the account ID with a real one from your org. Filtering on Type__c alone would fail, because it is not part of the index.
Platform events
A platform event (__e) is a message. You define its fields in the same way as a custom object, but publishing an event does not create a record you can edit or report on. Subscribers receive the message and react.
Typical uses are telling an external system that an invoice was paid, decoupling a long-running process from the transaction that started it, and updating Lightning components in real time.
The flow is as follows:
- A publisher creates the event. The publisher can be Apex, a flow, or an external system using the API.
- The event bus delivers it to every subscriber.
- Each subscriber handles it. Subscribers can be Apex triggers, flows, Lightning components using
empApi, or external clients using CometD or the Pub/Sub API.
Assume a platform event Invoice_Paid__e with a text field Invoice_Number__c and a number field Amount__c. This Apex publishes it:
Invoice_Paid__e evt = new Invoice_Paid__e(
Invoice_Number__c = 'INV-0001',
Amount__c = 1200
);
Database.SaveResult result = EventBus.publish(evt);
if (!result.isSuccess()) {
for (Database.Error err : result.getErrors()) {
System.debug('Publish failed: ' + err.getMessage());
}
}An Apex trigger subscribes to it:
trigger InvoicePaidSubscriber on Invoice_Paid__e (after insert) {
for (Invoice_Paid__e evt : Trigger.new) {
System.debug('Invoice paid: ' + evt.Invoice_Number__c + ' for ' + evt.Amount__c);
}
}Event triggers support only after insert. They run in their own transaction, separate from the publisher's.
Gotchas
- Publish behavior. An event can be set to Publish After Commit or Publish Immediately. With after commit, a rolled-back transaction publishes nothing. With immediate publishing, the event is sent even if the transaction later fails.
- Retention. The event bus keeps recent events for replay, for about 72 hours. After that they are gone. Subscribers that go offline can catch up by replaying from a stored replay ID within that window.
- No guaranteed ordering across subscribers or retries. Make handlers idempotent, so a repeated event has no ill effect.
- Limits. Publishing counts against hourly event allocations and per-transaction DML-style limits.
Choosing among the four
| If you need to... | Use |
|---|---|
| Ship a list of rates or flags with your deployment | Custom metadata type |
| Show orders from an ERP without copying them | External object |
| Keep 500 million log rows and read them by account and date | Big object |
| Tell other systems that something happened | Platform event |
| Store ordinary business records with sharing and reports | Custom object |
Exercise
A team stores a table of shipping rates in a custom object. They must re-enter the rows in every sandbox after each refresh, and Apex runs a SOQL query on each shipment. Which entity type fits better, and which two problems does it solve?
Show answer
A custom metadata type (__mdt). Its records deploy with change sets, packages or Salesforce DX, so nobody re-enters them after a sandbox refresh. Apex can read them with getInstance() or getAll(), which does not count against the SOQL query limit.
Exercise
A big object has the index Account_c, then CreatedAt_c. Which query fails: (a) filter on Accountc only, (b) filter on Accountc and a CreatedAt_c range, (c) filter on CreatedAt__c only? Why?
Show answer
Query (c) fails. A big object query must filter on the index fields in order, starting with the first one. Filtering on CreatedAtc without Account_c skips the leading index field. Queries (a) and (b) both follow the index order.
Exercise
An Apex transaction publishes a platform event set to Publish After Commit, then throws an unhandled exception. Do subscribers receive the event?
Show answer
No. With Publish After Commit, the event is sent only if the transaction commits. The exception rolls the transaction back, so nothing is published. With Publish Immediately, the event would have been sent anyway.