Batch Writing

Updated at:
Copy as MD

Batch writing (buffer) collects high-frequency, fragmented messages and processes them into memories in bulk. This reduces write overhead in real-time conversations and event streams, while producing memories with richer context.

Problems addressed

Without batch writing, high-frequency message ingestion may cause the following issues:

  • Each message triggers a separate model invocation, which is costly and slow.

  • Fragmented messages such as acknowledgments or partial sentences cannot produce meaningful memories on their own.

  • High-frequency writes become a bottleneck in the agent pipeline.

Capabilities

Capability

Description

Automatic batching

Messages are held in a buffer and automatically consolidated into memories when a threshold is reached or a timeout expires. No client-side orchestration is required.

User and tag isolation

Messages from different users or with different metadata are batched separately. The resulting memories retain the original metadata.

Manual flush

Trigger consolidation immediately at session end or other milestones, without waiting for the automatic trigger.

Queryable status

Check how many messages are buffered and how long they have been waiting for any user.

Tunable cadence

View and adjust the batching trigger cadence to match your message volume.

Automatic retry on failure

Messages that fail consolidation are not lost. The system retries automatically until processing succeeds.

Use cases

  • Real-time conversation streams: Reduce write costs as user messages arrive one by one.

  • IoT and event streams: Accumulate high-frequency device events before forming memories.

  • Multi-turn short-message sessions: Merge low-information messages to extract complete conclusions.

  • Bulk import: Scenarios that are insensitive to write latency but sensitive to cost.

Usage

Operation

Endpoint

Description

Write to buffer

POST /memories/buffer

Same parameters as memory writing. Returns immediately in asynchronous mode by default.

Manual flush

POST /memories/flush

Immediately trigger batch consolidation for a specified user.

Check buffer status

GET /memories/buffer/status?user_id=xxx

View the number of buffered messages and their wait time.

View batch config

GET /memories/buffer/config

View the current batching trigger cadence.

Adjust batch config

PUT /memories/buffer/config

Adjust the batching cadence. Changes take effect immediately.

Use async_mode to control the return behavior: the default value true returns immediately and processes in the background. Set it to false for synchronous mode that waits for and returns the complete result, which is suitable for critical writes that require persistence confirmation.

Note

Buffered messages are not searchable until they are consolidated into the memory store. For messages that must be visible immediately after writing, use the standard POST /memories endpoint instead.

View and adjust batch configuration

View the current configuration:

curl -sS "${MEMORY_URL}/memories/buffer/config" \
  -H "Authorization: Token ${MEMORY_API_KEY}"

Sample response:

{
  "char_threshold": 10000,
  "time_threshold_seconds": 1800,
  "scan_interval_seconds": 300,
  "retry_alert_threshold": 5
}

The following table describes the parameters.

  • char_threshold: The character count threshold that triggers consolidation. Consolidation is triggered when the buffered messages for a group reach this cumulative character count.

  • time_threshold_seconds: The maximum wait time in seconds. Consolidation is triggered even if the character threshold is not reached but this duration has elapsed.

  • scan_interval_seconds: The interval in seconds at which the system checks the buffer.

  • retry_alert_threshold: The number of consecutive consolidation failures that triggers an alert.

Modify configuration as needed. Submit only the fields you want to change. Invalid parameters return a 400 error.

curl -sS -X PUT "${MEMORY_URL}/memories/buffer/config" \
  -H "Authorization: Token ${MEMORY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"char_threshold": 5000}'

Example

The following example writes three fragmented messages to the buffer, manually triggers consolidation, and checks the result.

Note

Pass the API key through environment variables. Do not hardcode it in code or public documentation.

Step 1: Configure the endpoint and credentials

export MEMORY_URL="https://api-longmemory-cn-beijing.opentrust.net"
export MEMORY_API_KEY="<Replace with your API Key>"
export USER_ID="demo-user-001"

Step 2: Write three messages to the buffer

curl -sS -X POST "${MEMORY_URL}/memories/buffer" \
  -H "Authorization: Token ${MEMORY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"I am going on a business trip to Hangzhou next week"}],"user_id":"'${USER_ID}'","async_mode":false}'
curl -sS -X POST "${MEMORY_URL}/memories/buffer" \
  -H "Authorization: Token ${MEMORY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"I also want to visit West Lake while I am there"}],"user_id":"'${USER_ID}'","async_mode":false}'
curl -sS -X POST "${MEMORY_URL}/memories/buffer" \
  -H "Authorization: Token ${MEMORY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Recommend a hotel near West Lake"}],"user_id":"'${USER_ID}'","async_mode":false}'

In synchronous mode, messages return a status of buffered when they enter the buffer. If the write happens to trigger consolidation, the response returns flush_triggered.

Step 3: Trigger consolidation manually

curl -sS -X POST "${MEMORY_URL}/memories/flush" \
  -H "Authorization: Token ${MEMORY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"user_id":"'${USER_ID}'"}'

The endpoint returns 202, indicating that the consolidation task is accepted and running in the background.

Step 4: Check the consolidated memories

curl -sS "${MEMORY_URL}/memories?user_id=${USER_ID}" \
  -H "Authorization: Token ${MEMORY_API_KEY}"

The three fragmented messages are merged into a single, more complete memory:

{
  "results": [
    {
      "memory": "The user is traveling to Hangzhou next week for business and plans to visit West Lake. Looking for a hotel near West Lake."
    }
  ],
  "total": 1
}

If each message were written individually, none of them would produce a meaningful memory on its own. Batching them together saves model invocations and produces a more complete result.

Best practices

  • Use batch writing for high-frequency, low-value messages. Use standard writing for critical facts. One-time critical information such as explicit user declarations should be written directly through POST /memories for immediate persistence.

  • Trigger a manual flush at session end. This prevents residual messages from waiting for the timeout before they are stored, and ensures memory timeliness.

  • Accept the delay between writing and searchability. Batch writing trades real-time visibility for cost and quality. Do not use batching for paths that require immediate search availability.

  • Use synchronous mode for critical writes. Set async_mode=false to receive persistence confirmation.

  • Tune the batching cadence to your message volume. Decrease char_threshold when message volume is low and you want memories available sooner. Increase it for high-volume, latency-insensitive scenarios to further reduce costs.

  • Use the status endpoint for monitoring. If the pending count keeps growing with long wait times, the user's message volume is consistently low. Consider triggering consolidation proactively.