There is a lex chatbot created in AWS.Session timeout is not getting detected in lex chatbot despite configuring the session timeout to 1 minute.
Even lambda function created on the code hook intent invocation for lex chatbot is also not detecting session timeout on the chatbot.
The code for lambda function is as follows:
import boto3
import json
from datetime import datetime, timedelta, timezone
Initialize DynamoDB resource and table
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('LexSessionTable')
Session timeout in minutes
SESSION_TIMEOUT_MINUTES = 1
def lambda_handler(event, context):
print("FULL EVENT:", json.dumps(event, indent=2)) # Debug log
# Safely extract sessionId
session_id = event.get('sessionId')
if not session_id:
raise ValueError("Missing 'sessionId' in Lex event payload.")
now = datetime.now(timezone.utc)
# Fetch session from DynamoDB
try:
response = table.get_item(Key={'sessionId': session_id})
session_data = response.get('Item')
print(f"Session data: {session_data}")
except Exception as e:
print(f"Error accessing DynamoDB: {e}")
session_data = None
if session_data:
try:
last_interaction = datetime.fromisoformat(session_data['lastInteractionTime'])
print(f"Last interaction time: {last_interaction}")
if now - last_interaction > timedelta(minutes=SESSION_TIMEOUT_MINUTES):
# Session expired
print("Session expired")
table.delete_item(Key={'sessionId': session_id})
return {
"sessionState": {
"dialogAction": {"type": "Close"},
"intent": {"name": "FallbackIntent", "state": "Fulfilled"},
"sessionAttributes": {},
},
"messages": [{
"contentType": "PlainText",
"content": "Your session has expired. Let's start over."
}]
}
else:
# Update timestamp
print("Updating session timestamp")
table.update_item(
Key={'sessionId': session_id},
UpdateExpression="SET lastInteractionTime = :time",
ExpressionAttributeValues={':time': now.isoformat()}
)
except Exception as e:
print(f"Error processing session data: {e}")
else:
# New session
try:
print("Creating new session")
table.put_item(Item={
'sessionId': session_id,
'lastInteractionTime': now.isoformat()
})
except Exception as e:
print(f"Error creating new session: {e}")
# Continue with Lex logic
return {
"sessionState": event.get("sessionState", {}),
"messages": [{
"contentType": "PlainText",
"content": "Session is active."
}]
}
Cloudwatch Log:
{
"timestamp": "2025-06-09T13:17:18.789Z",
"requestId": "635cbabc-7631-4e93-96e5-edd5bf0f7362",
"messages": [
{
"contentType": "PlainText",
"content": "Hey, what is your name ?"
}
],
"messageVersion": "2.0",
"dialogEventLogs": [
{
"dialogStepLabel": "Intent/GreetIntent/StartIntent",
"nextStep": {
"dialogAction": {
"type": "InvokeDialogCodeHook"
}
}
},
{
"dialogStepLabel": "Intent/GreetIntent/StartIntent/CodeHook/Success",
"nextStep": {
"dialogAction": {
"type": "ElicitSlot",
"slotToElicit": "UserName"
}
}
}
],
"transcriptions": [
{
"transcription": "hi",
"transcriptionConfidence": 1,
"resolvedContext": {
"intent": "GreetIntent"
},
"resolvedSlots": {}
}
],
"sessionId": "189693864019378",
"isTestWorkbenchTraffic": false,
"inputMode": "Text",
"operationName": "RecognizeText",
"interpretations": [
{
"intent": {
"name": "GreetIntent",
"state": "InProgress",
"slots": {
"UserName": null
},
"confirmationState": "None"
},
"interpretationSource": "Lex",
"nluConfidence": "1.00"
},
{
"intent": {
"name": "FallbackIntent",
"slots": {}
},
"interpretationSource": "Lex"
},
{
"intent": {
"name": "GoodbyeIntent",
"slots": {}
},
"interpretationSource": "Lex",
"nluConfidence": "0.49"
},
{
"intent": {
"name": "ThankYouIntent",
"slots": {}
},
"interpretationSource": "Lex",
"nluConfidence": "0.46"
},
{
"intent": {
"name": "Help_Intent",
"slots": {}
},
"interpretationSource": "Lex",
"nluConfidence": "0.32"
}
],
"developerOverride": false,
"bot": {
"name": "DC_GP",
"version": "DRAFT",
"id": "0QKBBZUGLZ",
"aliasName": "TestBotAlias",
"aliasId": "TSTALIASID",
"localeId": "en_GB"
},
"sessionState": {
"sessionAttributes": {},
"dialogAction": {
"type": "ElicitSlot",
"slotToElicit": "UserName"
},
"intent": {
"name": "GreetIntent",
"state": "InProgress",
"slots": {
"UserName": null
},
"confirmationState": "None"
},
"originatingRequestId": "1a0e2561-ff28-45b5-9bd8-fc260e41b641"
},
"inputTranscript": "hi",
"missedUtterance": false,
"utteranceContext": {}
}
{"timestamp":"2025-06-09T13:17:18.789Z","requestId":"635cbabc-7631-4e93-96e5-edd5bf0f7362","messages":[{"contentType":"PlainText","content":"Hey, what is your name ?"}],"messageVersion":"2.0","dialogEventLogs":[{"dialogStepLabel":"Intent/GreetIntent/StartIntent","nextStep":{"dialogAction":{"type":"InvokeDialogCodeHook"}}},{"dialogStepLabel":"Intent/GreetIntent/StartIntent/CodeHook/Success","nextStep":{"dialogAction":{"type":"ElicitSlot","slotToElicit":"UserName"}}}],"transcriptions":[{"transcription":"hi","transcriptionConfidence":1.0,"resolvedContext":{"intent":"GreetIntent"},"resolvedSlots":{}}],"sessionId":"189693864019378","isTestWorkbenchTraffic":false,"inputMode":"Text","operationName":"RecognizeText","interpretations":[{"intent":{"name":"GreetIntent","state":"InProgress","slots":{"UserName":null},"confirmationState":"None"},"interpretationSource":"Lex","nluConfidence":"1.00"},{"intent":{"name":"FallbackIntent","slots":{}},"interpretationSource":"Lex"},{"intent":{"name":"GoodbyeIntent","slots":{}},"interpretationSource":"Lex","nluConfidence":"0.49"},{"intent":{"name":"ThankYouIntent","slots":{}},"interpretationSource":"Lex","nluConfidence":"0.46"},{"intent":{"name":"Help_Intent","slots":{}},"interpretationSource":"Lex","nluConfidence":"0.32"}],"developerOverride":false,"bot":{"name":"DC_GP","version":"DRAFT","id":"0QKBBZUGLZ","aliasName":"TestBotAlias","aliasId":"TSTALIASID","localeId":"en_GB"},"sessionState":{"sessionAttributes":{},"dialogAction":{"type":"ElicitSlot","slotToElicit":"UserName"},"intent":{"name":"GreetIntent","state":"InProgress","slots":{"UserName":null},"confirmationState":"None"},"originatingRequestId":"1a0e2561-ff28-45b5-9bd8-fc260e41b641"},"inputTranscript":"hi","missedUtterance":false,"utteranceContext":{}}
So basically session timeout is not working at lex chatbot level. The issue is persistent since last week and we as a team are unable to find a workaround despite having tried out all possible methods.