
The Agent Is Just Another Client: Safe Database Writes with Strands Agents on AWS
Learn how a chat agent can add plants and log actions in DynamoDB through the same validated code as your REST endpoints, with user and garden IDs that the model can never supply or change.
An application where the user can chat with an agent and the agent has access to modify the database. Sounds practical, but how do you make sure that the agent is not going to cause havoc? That's what this article examines with a simple demo example using AWS Lambda, Strands Agents, Amazon DynamoDB and Bedrock. All code can be found in this GitHub repository , and the README file includes the exact commands for creating the project locally and deploying it on your own AWS account.
Background
The application I am describing in this article is a simple backend for a gardening mobile/web application. In real life, that would of course require things like authentication and an API Gateway in front of the Lambda function, but I have left them out of this project in order to keep things as simple as possible.
The backend is built for the basic functionality that the frontend application is going to require. It is going to have screens where the user can add new plants, get information about their plants and add logs for actions like watering or treatments. In addition, there will be a chat functionality where the user can ask questions about their plants and receive care instructions. The idea is that the application will work as the user's 'memory' (when did I water this tree last time, have I given this plant any fertiliser) and, in addition, advise the user when they get stuck - helpful especially for those who desperately want to start gardening in this era of AI but lack the experience.
Setting up
The code can be found in the above-mentioned repository with full instructions in the README file. The infrastructure contains an AWS Lambda function and a DynamoDB table, provisioned using a CloudFormation template. The project is easy to set up by configuring your AWS credentials, creating an S3 bucket for the deployment zip, packaging the Lambda and uploading it to S3 and deploying the CloudFormation stack.
As described in the diagram below, the agent and the REST API routes use the same shared functions before interacting with DynamoDB. The agent connects to the Bedrock Nova Pro model via an agentic loop, which is the iterative execution cycle where an AI agent takes actions (such as calling a tool) and evaluates the result until it meets the goal. In addition, the agent has a tool that lets it fetch data from a third-party weather API.

Once your application is deployed and the function URL is available, you can chat with the gardening agent synchronously from your terminal using curl:

Now that the basic project is running, let's look into the architectural decisions in more detail.
What needs a deterministic approach
Because the application needs several functionalities unrelated to conversational chat, make sure any fixed inputs and outputs go through endpoints, and only anything needing interpretation goes through the agent. You wouldn't want to spend money running the agentic loop when it is not necessary, and it is also the less reliable path. An agent always introduces an element of uncertainty—it can misinterpret context, take detours, or make mistakes.
For this demo, our gardening app needs the functionality to call the following endpoints:
- list plants
- add a new plant
- get a dashboard summary
- get a single plant
- list action logs for a plant (paginated)
- create an action log
Each of these endpoints will be implemented as traditional API endpoints (for this demo, as a function URL).
The agent's tools
An important decision that we have to make, of course, is the tools we are giving our agent. As I mentioned, the user could chat with the agent asking for advice and information about their plants. In order to answer these questions, the agent would at least need to be able to retrieve data from the database. But what about saving data in the database - the decision regarding that would be an important architectural decision to make.
From the user's perspective, it would be a lot easier if they could mention in the chat new plants or actions and didn't have to leave the chat to fill out some kind of forms manually, so we should give the agent the ability to add some data in the database. And this is where the design becomes interesting - we are essentially saying that our agent can implement the same actions that the REST API endpoints can. But how exactly should that happen? Imagine a situation where you give an agent a loose instruction to add a plant in the database if the user requests that. What's the schema that the agent would use? How would you make sure it ends up in the right user's garden and has all the requested attributes? When the user next opens their application, they might see something that doesn't make sense, maybe some cryptic undefined values or maybe the application would even crash if the frontend couldn't figure out how to display the data.
Making sure that the agent implements database actions correctly
As mentioned above, our main goal is to make sure that the agent is working exactly like an API endpoint would. This can be achieved by creating a shared service that deals with all of the database transactions. The agent is essentially just another client of the service that gets no special access. It goes through the same rules as the REST API.
As there is no authentication layer in this demo, the user ID and garden ID are injected by middleware. In a real application, there would of course be authentication and the ID would be taken from a verified token. Regardless, there are guardrails in place to make sure that the application is using the id's the application sets. The IDs are set by the middleware in code, before the model runs outside of the LLM's reach. The model can't supply or change them. The shared function that the REST API endpoints and the model are using also has a layer of protection, as it checks that a plant exists in that garden before taking any actions. Essentially the model is only able to decide which and what action it is working on. The actual garden is decided in code before the model runs, and every tool is reading it directly from the code.
The diagram below shows the core guardrail of the model not being able to supply or change the user ID and garden ID. There is also an additional soft-layer guardrail, which is the system prompt telling the model to refuse requests about other users, which is not 100% reliable, as it relies on the model:

The simplified code snippet below from
agent_runner.py shows how Strands builds the tool schema the model sees from this signature and docstring; no user ID or garden ID parameters exist here:@tooldef create_action_log( instance_id: str, action_type: str, notes: str = "", title: str = "", severity: str = "",) -> str: """Record an action the user has taken with a specific plant.
Args: instance_id: The plant instance identifier (e.g. 'tomato-01'). action_type: One of: watered, pruned, fertilised, issue_found, repotted, other. notes: Optional free-text description of what was done. title: Optional short title for the log entry. severity: Optional severity for issue_found entries. One of: mild, moderate, severe. """
The simplified code snippet below from
agent_runner.py shows how binding the garden before the agent runs happens. If there is no bound garden, no read or write is going to happen at all:from contextvars import ContextVar
# Set by code before the agent runs. The model has no way to write to it._authorized_garden_id: ContextVar[str | None] = ContextVar( "authorized_garden_id", default=None)
def run_chat(garden_id: str, message: str) -> str: # garden_id comes from require_garden (in production: the verified JWT). token = _authorized_garden_id.set(garden_id) try: agent = Agent(tools=[get_weather, get_garden_plants, add_plant, create_action_log, ...], ...) return str(agent(message)) finally: # A warm Lambda container reuses this context for the next invocation. _authorized_garden_id.reset(token)
@tooldef create_action_log(instance_id: str, action_type: str, ...) -> str: garden_id = _authorized_garden_id.get() if not garden_id: # Fail closed: no bound garden means no read or write at all. return "Error: No authorized garden context for this request." # ...
The validation in the shared function (
garden_service.py ) looks like the following:def create_action_log(garden_id: str, instance_id: str, action_type: str | None, ...): """Called by both POST /plants/{id}/action-logs and the agent tool."""
# The plant must exist in *this* garden. Another user's plant ID # gets the same 404 as one that doesn't exist. plant = garden_data.get_plant(garden_id, instance_id) if not plant: raise ApiError(404, "not_found", f"Plant '{instance_id}' not found in this garden.")
if not action_type: raise ApiError(400, "missing_field", "'action_type' is required.")
item = { # Raises a 400 listing the valid values if action_type isn't in the enum. "action_type": validate_enum("action_type", action_type, ActionType), # ...severity, logged_by, timestamps: validated the same way } garden_data.put_log(garden_id=garden_id, instance_id=instance_id, item=item, ...)
The idea of the above service layer is that the REST APIs get the garden_id from require_garden, the agent gets it from the context, and both call the same function.
The project also contains unit tests that make sure tool schemas contain no ID parameters, tools refuse without a bound garden, and another garden's plant ID returns 404:

You can run the tests locally using instructions in the README file.
Seeing it work
I made some tests before implementing the guardrails just to demonstrate how the LLM tries to be helpful and fulfil requests that clearly are not following the way our application should be working. Below, I asked the agent to add a tree for another user, and the logs show that the LLM decided to create a mock plant instance ID for this, as it didn't have the actual IDs available:

After the guardrails were in place, the logs for a similar request, adding a plant to another user's garden, simply show that the LLM is refusing to implement it:

I also tested whether the LLM would be able to, or attempted to, give me my user ID, which it refused to do:

Next, I tested requests that are not garden-related, and it managed to refuse to implement actions that don't relate to plants:

All of the above examples would require more thorough testing to confirm how the behaviour changes if the soft layer guardrail is removed or modified from the prompt.
An example of a happy path is shown below. The LLM is able to find out that the user has watered the plant already today and also yesterday. It can also fetch the current weather and give care instructions based on that information:

Limitations and conclusions
In the end, a few words on the limitations of this demo project. First of all, the garden-scoping guardrails are enforced in code, but the "decline requests about other users" behaviour depends on the model following the prompt, and the tests check the code, not the model. There are also other type os failures that could still happen, and we don't have any way of catching them yet - such as the model logging actions to the wrong plant in the user's own garden.
Furthermore, the chat history is saved in the same DynamoDB table and reloaded on the next message, so the agent can follow the conversation. This is a workable solution for this demo as it allows us to have a continuous conversation. There is, of course, a limitation as the whole conversation is stored and sent back each time, so long conversations will hit DynamoDB's 400 KB item limit and grow the prompt and the cost. This would be improved for a real production use case, but we will leave those considerations out of the scope of this article.
The lack of authentication is another big limitation. The Function URL is public, and every caller is treated as the one hardcoded demo user and garden. So anyone with the URL can read and change that garden and run up Bedrock costs, and the only cap is the optional reserved concurrency.
For clarity, it is also worth mentioning that the repository contains an async dashboard functionality that is not covered in this article. It allows the user to trigger a dashboard refresh with an API call, which leaves the agent to asynchronously create a dashboard summary. The user can then fetch the summary using another API endpoint.
The main takeaway from building this demo project has been that you shouldn't trust the model not to misbehave, but build guardrails that make the worst failures impossible. And verifying that it actually works is the most crucial step. Further testing on this demo would undoubtedly reveal how these guardrails can be further tightened.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article