• I know you must Bulkify your code.
  • Does this mean you have to expect UserInfo.getUserId() to be different users?
    • I.E. Can the same trigger can be called on multiple records for multiple users in the same execution. Or will it always be the same user?

No. Every non-test transaction has exactly one context user. A trigger may be invoked with a set of records with different owners, but the context user for the transaction will be constant.

In a unit test context only, the running user may change in a System.runAs() construct. This is not possible in normal Apex, though.

Platform Events triggers may receive events in a batch that were posted under different context users, but the trigger itself runs in the context of the Automated Process user for all of those events.

Other situations that appear to change context user, such as calling out to the Salesforce API through a Named Credential, really initiate a new transaction with a different context user.

| improve this answer | |
  • Is there documentation on this regarding 'Every non-test transaction...'? – shmuels Dec 27 '18 at 20:24
  • 2
    @shmuels There is documentation on transactions. I'm not sure it's explicitly documented that the running user doesn't change during a transaction, but there's a lot of machinery in the platform that wouldn't make sense if that could happen. with sharing classes, for example, would exhibit a lot of weird edge cases vis-a-vis record visibility. – David Reed Dec 27 '18 at 20:27
  • Just to add, because Platform Event triggers in specific always run as Automated Process, you'd be best to check the CreatedById field on the event instances whenever you care about "who" initiated the event. – Charles T Dec 28 '18 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.