Class LambdaMetadataClient

java.lang.Object
software.amazon.lambda.powertools.metadata.LambdaMetadataClient
All Implemented Interfaces:
org.crac.Resource

public final class LambdaMetadataClient extends Object implements org.crac.Resource
Client for accessing Lambda execution environment metadata.

This utility provides idiomatic access to the Lambda Metadata Endpoint (LMDS), eliminating boilerplate code for retrieving execution environment metadata like Availability Zone ID.

Features:

  • Automatic caching for the sandbox lifetime
  • Thread-safe access for concurrent executions
  • SnapStart cache invalidation via CRaC
  • Lazy loading on first access

Basic Usage


 public String handleRequest(Object input, Context context) {
     LambdaMetadata metadata = LambdaMetadataClient.get();
     String azId = metadata.getAvailabilityZoneId();
     return "{\"az\": \"" + azId + "\"}";
 }
 

Eager Loading


 public class MyHandler implements RequestHandler<Object, String> {
     // Fetch during cold start
     private static final LambdaMetadata METADATA = LambdaMetadataClient.get();

     public String handleRequest(Object input, Context context) {
         return "{\"az\": \"" + METADATA.getAvailabilityZoneId() + "\"}";
     }
 }
 
See Also:
  • Method Details

    • get

      public static LambdaMetadata get()
      Retrieves the cached metadata, fetching from the endpoint if not cached.

      This method is thread-safe and handles concurrent access correctly. The first call fetches metadata from the Lambda Metadata Endpoint, subsequent calls return the cached value.

      Returns:
      the LambdaMetadata instance
      Throws:
      LambdaMetadataException - if the metadata endpoint is unavailable or returns an error
    • beforeCheckpoint

      public void beforeCheckpoint(org.crac.Context<? extends org.crac.Resource> context)
      Called before a CRaC checkpoint is taken. Preloads classes to ensure faster restore.
      Specified by:
      beforeCheckpoint in interface org.crac.Resource
      Parameters:
      context - the CRaC context
    • afterRestore

      public void afterRestore(org.crac.Context<? extends org.crac.Resource> context)
      Called after a CRaC restore. Invalidates the cache since the AZ may have changed after cross-AZ restore.
      Specified by:
      afterRestore in interface org.crac.Resource
      Parameters:
      context - the CRaC context