首页 > 解决方案 > TooManyRequestsException:超出速率。在调用 codnito-idp admin_get_user 函数时

问题描述

我在我的 Python Lambda 函数中使用 AWS sdk 来获取 Cognito 用户的属性。像这样的代码:

     client = boto3.client('cognito-idp')
     try:            
        response = client.admin_get_user(
            UserPoolId=pool_id,
            Username=email
        )
        
        if response is not None and 'Username' in response and 'UserAttributes' in response:
            res = response['UserAttributes']
            return res
        else:
            return None
            
    except ClientError as e:
        if e.response['Error']['Code'] == 'UserNotFoundException':
            print("USER NOT FOUND")
            return None
        
        raise e
        
return None

当我尝试使用AdminGetUser API获取多个用户(大约 50 个用户)时,我收到 TooManyRequestsException 错误。

根据 AWS Doc,每秒从 Cognito 获取用户信息的默认限制是多少?我在 Amazon Cognito 中看到此页面配额,但我看不到此默认限制是多少。

处理这个问题的最佳方法是什么?

现在我打算等待 1 秒,然后我会尝试从同一个用户那里获取用户的属性,同时我得到相同的异常。

谢谢!

标签: pythonamazon-web-servicesaws-lambdaamazon-cognitoaws-serverless

解决方案


根据您提到的配额页面,限制是 5/秒。

Amazon Cognito 用户池 API 中的软限制
...
上面未列出的管理 API。5

您需要限制您的请求,但最佳方法取决于您的解决方案的其他方面。

几个例子:

如果你的 lambda 函数被调用 50 次,每个用户调用一次,你可以为你的 lambda 设置最大并发。(您可以在此处此处找到更多信息)。

如果单个 lambda 调用一次迭代所有 50 个项目,那么您可以time.sleep在每次迭代中添加一个调用,或者使用一些速率限制库(这个似乎可以完成任务:https ://pypi.org/project/ratelimit/ ) . 在这种情况下,除了这种方法之外,您可能还希望将 lambda 的并发限制为仅 1 。


推荐阅读