Skip to content

Commit

Permalink
Add documentation for using the client in FaaS environments
Browse files Browse the repository at this point in the history
  • Loading branch information
sethmlarson committed Aug 16, 2021
1 parent acf1e0d commit 74320f4
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions docs/guide/connecting.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,76 @@ es = Elasticsearch(
api_key=(“api_key_id”, “api_key_secret”)
)
----------------------------

[discrete]
[[connecting-faas]]
=== Using the Client in a Function-as-a-Service Environment

This section illustrates the best practices for leveraging the {es} client in a Function-as-a-Service (FaaS) environment.
The most influential optimization is to initialize the client outside of the function, the global scope.
This practice does not only improve performance but also enables background functionality as – for example –
https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[sniffing].
The following examples provide a skeleton for the best practices.

[discrete]
[[connecting-faas-gcp]]
==== GCP Cloud Functions

[source,py]
----------------------------
from elasticsearch import Elasticsearch
client = Elasticsearch(
... # Client initialization
)
def main(request):
... # Use the client
----------------------------

[discrete]
[[connecting-faas-aws]]
==== AWS Lambda

[source,py]
----------------------------
from elasticsearch import Elasticsearch
client = Elasticsearch(
... # Client initialization
)
def main(event, context):
... # Use the client
----------------------------

[discrete]
[[connecting-faas-azure]]
==== Azure Functions

[source,py]
----------------------------
import azure.functions as func
from elasticsearch import Elasticsearch
client = Elasticsearch(
... # Client initialization
)
def main(request: func.HttpRequest) -> func.HttpResponse:
... # Use the client
----------------------------

IMPORTANT: The async client shouldn't be used within Function-as-a-Service as a new event
loop must be started for each invocation. Instead the synchronous `Elasticsearch`
client is recommended.

Resources used to assess these recommendations:

* https://cloud.google.com/functions/docs/bestpractices/tips#use_global_variables_to_reuse_objects_in_future_invocations[GCP Cloud Functions: Tips & Tricks]
* https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html[Best practices for working with AWS Lambda functions]
* https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level#global-variables[Azure Functions Python developer guide]
* https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html[AWS Lambda: Comparing the effect of global scope]

0 comments on commit 74320f4

Please sign in to comment.