In my case, code supplied by the end user is compiled into a different language such that I think I can prevent intentionally-malicious activity.
Nonetheless, spinning up a VM to create an environment in which potentially untrustworthy code is executed before then destroying the VM seems the safest option.
Lambda allows arbitraty network access and may allow access to your AWS resources.
If you have to do this, the best approach is to containerise it, use capabilities to enforce restrictions and run in a virtual machine as isolated as possible.
It's still not great though. Some languages (eg Java) have additional features that help with this though.
I didn’t mention containers since they don’t provide strong isolation and some people misuse them as though they do. There’s no harm in using them as another layer of defense, but hardware virtualization provides much better security.