How to optimize a flow that uses internal memory?

Describe the problem/error/question

Im learning how to use the memory in order to store some flow data during execution. Im looking for the best way to unify lastStates and lastTimestamps into one single entity to later delete records where timestamp is older than 24 hours.

My code node is currently storing this in memory:

[
  {
    "debug_lastStates": {
      "1234567": "Preparacion"
    },
    "debug_lastTimestamps": {
      "1234567": 1754366490
    }
  }
]

I would like to adjust it so it stores it this way:


{
  "debug_lastData": {
    "1234567": {
      "state": "Preparacion",
      "timestamp": 1754366490
    }
  }
}

What is the error message (if any)?

Please share your workflow

This is the current code node i have (Python) which works ok but saves the same id with mergeable data in separate structures.

import time

# Obtengo la memoria global del workflow
workflowStaticData = _getWorkflowStaticData('global')

# Inicializo lastStates si no existe
if 'lastStates' not in workflowStaticData:
    workflowStaticData['lastStates'] = {}


# Limpieza de entradas antiguas (TTL de 48h)
TTL_SECONDS = 24 * 3600
now = int(time.time())

# Usamos una estructura auxiliar para guardar timestamps
if 'lastTimestamps' not in workflowStaticData:
    workflowStaticData['lastTimestamps'] = {}

lastTimestamps = workflowStaticData['lastTimestamps']

# Borramos claves expiradas
expired_keys = [
    k for k, ts in lastTimestamps.items()
    if now - ts > TTL_SECONDS
]
for k in expired_keys:
    workflowStaticData['lastStates'].pop(k, None)
    lastTimestamps.pop(k, None)
  

# Recojo todos los items como lista Python
items_to_notify = []
all_items = _input.all()

# Itero y comparo estados
for itm in all_items:
    data       = itm['json']
    key        = str(data['IdAtencion'])
    current    = data['Estado'].strip()
    last_state = workflowStaticData['lastStates'].get(key)
    telefono   = str(data.get('TelAcompanante', '')).strip()
    sede       = str(data.get('Sede', '')).strip()
  

    # Si no había notificado o cambió de estado:
    if last_state != current:
        # a) Actualizo la memoria global
        workflowStaticData['lastStates'][key] = current
        workflowStaticData['lastTimestamps'][key] = now

        # b) Marco este ítem con solo los campos requeridos
        items_to_notify.append({
            'json': {
                'Paciente':       data['Paciente'],
                'TelAcompanante': telefono,
                'Estado':         current,
                'Sede':           sede
            }
        })

# Devuelvo sólo los ítems que requieren POST
return items_to_notify

Share the output returned by the last node

Information on your n8n setup

  • n8n version: 1.97.1
  • Database (default: SQLite): default
  • n8n EXECUTIONS_PROCESS setting (default: own, main): default
  • Running n8n via (Docker, npm, n8n cloud, desktop app): Docker
  • Operating system: Debian

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.