0

I have the following sample code. This is run as Yandex.Functions (almost equal to AWS functions).

def handler(event, context):
    # some long processing is here
    text = result_of_long_processing()
    return {
        'response': {
            'text': text
        },
    }

I should modify the code in the following way:

  1. if long processing takes less than 3 seconds, then the result of this processing should be returned
  2. if it takes more than 3 seconds, then some standard text (like wait more) should be returned and the processing should be continued.

How could I achieve it?

LA_
  • 19,823
  • 58
  • 172
  • 308
  • Try using time module with it you can calculate time between 2 points in your code by setting start = time.time() and later end = time.time() and subtracting those two. – Uros Pocek Mar 30 '21 at 20:33

1 Answers1

2

This is run as Yandex.Functions (almost equal to AWS functions).

I'm going to answer based on this, and the short answer is that you can't.

A Lambda function returns some value at the end of its execution. It won't continue executing once you return. While you can create a background thread, that thread is suspended when the main thread returns a value.

Which means that you need to create a system architecture to support long-running tasks. At the least that involves:

  • Two Lambdas, one to perform processing and one to interact with caller.
  • Some place to store results, such as a Redis cache or database.

In such a system, your "gateway" function creates a unique identifier (typically a UUID). It then invokes the second "processing" function, passing it the UUID.

The processing function does its thing, and writes the results to the datastore, keyed by the UUID.

The "gateway" function can return that UUID immediately to the caller, or choose to wait (polling the datastore) for however much time you want to wait.

If the results were not available by the time the "gateway" finishes polling, the client will have to take over the responsibility: calling the "gateway" with the UUID until the results are available.

Parsifal
  • 3,928
  • 5
  • 9