Quando uma política de armazenamento em cache é executada, um cache L1 de curta duração é criado. Depois de um segundo, se um item armazenado em cache não for acessado, ele será mantido em um banco de dados onde ficará disponível para todos os processadores de mensagens implantados em um ambiente até que o cache expire.
O prazo de validade é configurado diretamente na política de cache.
Níveis de cache permanente e na memória
Os caches compartilhados e caches do ambiente são criados em um sistema de dois níveis composto por um nível
na memória e um nível permanente, conforme mostrado na figura a seguir. As políticas interagem com os dois níveis
como um framework combinado. A Apigee gerencia a relação entre os níveis.
O nível 1 é um cache na memória (L1) para acesso rápido. Cada nó de processamento de mensagens (MP, na sigla em inglês) tem o próprio cache na memória para uma resposta mais rápida às solicitações.
O L1 é um cache de curta duração (1 segundo), na memória.
À medida que o limite de memória é atingido, a Apigee remove entradas de cache da memória (embora
ainda sejam mantidas no cache persistente L2) para garantir que a memória permaneça disponível
para outros processos.
O L1 é fornecido com cache de curta duração de um segundo para executar pesquisas mais rápidas
em solicitações simultâneas com a mesma chave de cache.
O nível 2 é um cache permanente (L2) abaixo do cache na memória. Todos os nós de processamento de
mensagens compartilham um armazenamento de dados em cache (Cassandra) para manter as entradas de cache persistentes.
As entradas de cache persistem, mesmo após serem removidas do cache L1, como quando
os limites na memória são atingidos.
Como o cache permanente é compartilhado entre os processadores de mensagens (mesmo em diferentes
regiões), as entradas de cache estarão disponíveis independentemente de qual nó receber uma solicitação de
dados em cache.
Somente entradas de um determinado tamanho podem ser armazenadas em cache, e outros limites podem ser aplicados.
Consulte Como gerenciar limites de cache.
O conteúdo do cache em L2 é criptografado com o algoritmo AES-256.
Os dados são descriptografados antes de serem usados pelo ambiente de execução e
criptografados antes de serem gravados em L2. Assim, o processo de criptografia fica invisível para os usuários.
Como as políticas usam o cache
Veja a seguir como a Apigee lida com entradas de cache de acordo com o funcionamento de suas políticas de armazenamento
em cache.
Quando uma política grava uma nova entrada no cache (política PopulateCache ou
ResponseCache):
A Apigee grava a entrada no cache L1 na memória apenas no processador de mensagens
que processou a solicitação. Se os limites de memória do processador de mensagens forem atingidos,
antes que a entrada expire, a Apigee removerá a entrada do cache L1.
A Apigee também grava a entrada no cache L2.
Quando uma política lê do cache (política LookupCache ou ResponseCache):
A Apigee procura primeiro a entrada no cache L1 na memória do processador de mensagens que
processa a solicitação.
Se não houver uma entrada correspondente na memória, a Apigee procura a entrada no cache
permanente L2.
O processador de mensagens que recebe a solicitação exclui a entrada do cache
L1 de um segundo na memória e também exclui a entrada do cache L2.
Após uma atualização ou invalidação, é possível que os outros processadores de mensagens
permaneçam no cache L1 na memória.
Como o L1 está configurado para expirar em um segundo, nenhum evento de exclusão/atualização é
necessário para remover a entrada do L1.
Como gerenciar limites de cache
Por meio da configuração, você pode gerenciar alguns aspectos do cache O espaço total
disponível para o cache na memória é limitado pelos recursos do sistema e não é configurável.
As seguintes restrições se aplicam ao cache:
Limites de cache: vários limites de cache
se aplicam, como nome e tamanho do valor, número total de caches, número de itens em um cache
e expiração.
Cache na memória (L1). Não é possível configurar limites de memória para seu cache. Os limites
são definidos pela Apigee para cada processador de mensagens que hospeda caches para vários clientes.
Em um ambiente de nuvem hospedado, em que os caches na memória de todas as implantações de clientes são hospedados
em vários processadores de mensagens compartilhadas, cada processador conta com um limite de
porcentagem de memória configurável da Apigee para garantir que o armazenamento em cache não consuma toda a memória do
aplicativo. threshold medida que o limite é ultrapassado para um determinado processador de mensagens, as entradas de cache são eliminadas
da memória de acordo com a forma usada recentemente. As entradas excluídas da memória permanecem no cache L2
até expirar ou serem invalidadas.
Cache permanente (L2). As entradas removidas do cache na memória
permanecem no cache persistente de acordo com as configurações configuráveis de tempo de vida.
Otimizações configuráveis
A tabela a seguir lista as configurações que você pode usar para otimizar o desempenho do cache.
Configuração
Descrição
Observações
Expiração
Especifica o tempo de vida para entradas de cache.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-03 UTC."],[[["\u003cp\u003eThis documentation covers the caching mechanisms for Apigee and Apigee hybrid, focusing on how caching policies interact with the underlying cache system.\u003c/p\u003e\n"],["\u003cp\u003eApigee uses a two-level cache system, including a short-lived, in-memory L1 cache for rapid access and a persistent L2 cache for storing entries beyond L1's lifespan.\u003c/p\u003e\n"],["\u003cp\u003eCache policies, such as PopulateCache, LookupCache, InvalidateCache, and ResponseCache, interact with both L1 and L2 caches to write, read, update, and invalidate entries.\u003c/p\u003e\n"],["\u003cp\u003eWhen a cache entry is written, it is stored in both L1 and L2, and when read, Apigee first checks L1, then L2 if not found, while updates or invalidations remove the entry from both levels.\u003c/p\u003e\n"],["\u003cp\u003eWhile L1 memory limits are managed by Apigee, the persistent L2 cache retains evicted entries until expiration, and configurable settings like expiration times can be adjusted to optimize cache performance.\u003c/p\u003e\n"]]],[],null,["# Cache internals\n\n*This page\napplies to **Apigee** and **Apigee hybrid**.*\n\n\n*View [Apigee Edge](https://docs.apigee.com/api-platform/get-started/what-apigee-edge) documentation.*\n\nThis topic describes the workings of the cache beneath policies such as the\n[PopulateCache policy](/apigee/docs/api-platform/reference/policies/populate-cache-policy), [LookupCache policy](/apigee/docs/api-platform/reference/policies/lookup-cache-policy), [InvalidateCache policy](/apigee/docs/api-platform/reference/policies/invalidate-cache-policy), and\n[ResponseCache policy](/apigee/docs/api-platform/reference/policies/response-cache-policy).\n\nAbout caches\n------------\n\nWhen a caching policy executes, a short-lived, L1 cache\nis created. After one second, if a cached item is not accessed, it is persisted in a database\nwhere it is available to all message processors deployed in an environment until the cache expires.\nYou configure the expiration time directly in the cache policy.\n| **Note:** [List](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.environments.caches/list) and [delete](https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.environments.caches/delete) are the only cache API operations available.\n\nIn-memory and persistent cache levels\n-------------------------------------\n\nBoth the shared and environment caches are built on a two-level system made up of an in-memory\nlevel and a persistent level as shown in the following figure. Policies interact with both levels\nas a combined framework. Apigee manages the relationship between the levels.\n| **Note:** For more information on the cache policies, see: [PopulateCache](/apigee/docs/api-platform/reference/policies/populate-cache-policy), [LookupCache](/apigee/docs/api-platform/reference/policies/lookup-cache-policy), [InvalidateCache](/apigee/docs/api-platform/reference/policies/invalidate-cache-policy), and [ResponseCache](/apigee/docs/api-platform/reference/policies/response-cache-policy).\n\n- **Level 1 is an in-memory cache (L1)** for fast access. Each message processing (MP) node has its own in-memory cache for the fastest response to requests.\n - L1 is a short-lived (1 second), in-memory cache.\n - As the memory limit is reached, Apigee removes cache entries from memory (although they are still kept in the L2 persistent cache) to ensure that memory remains available for other processes.\n - L1 is provided with short-lived one-second cache to perform faster lookups for concurrent requests with the same cache key.\n- **Level 2 is a persistent cache (L2)** beneath the in-memory cache. All message processing nodes share a cache data store (Cassandra) for persisting cache entries.\n - Cache entries persist here even after they are removed from L1 cache, such as when in-memory limits are reached.\n - Because the persistent cache is shared across message processors (even in different regions), cache entries are available regardless of which node receives a request for the cached data.\n - Only entries of a certain size may be cached, and other cache limits apply. See [Managing cache limits](#cachelimits).\n - The cache content in L2 is encrypted with the AES-256 algorithm. Data is decrypted before being used by the runtime and is encrypted before being written into L2. So the encryption process is invisible to users.\n\nHow policies use the cache\n--------------------------\n\nThe following describes how Apigee handles cache entries as your caching policies do\ntheir work.\n\n- When a policy **writes a new entry** to the cache (PopulateCache or ResponseCache policy):\n 1. Apigee writes the entry to the in-memory L1 cache on only the message processor that handled the request. If the memory limits on the message processor are reached before the entry expires, then Apigee removes the entry from L1 cache.\n 2. Apigee also writes the entry to L2 cache.\n- When a policy **reads** from the cache (LookupCache or ResponseCache policy):\n 1. Apigee looks first for the entry in the in-memory L1 cache of the message processor handling the request.\n 2. If there is no corresponding in-memory entry, Apigee looks for the entry in the L2 persistent cache.\n 3. If the entry is not in the persistent cache:\n - [LookupCache policy](/apigee/docs/api-platform/reference/policies/lookup-cache-policy): No value is retrieved from the cache.\n - [ResponseCache policy](/apigee/docs/api-platform/reference/policies/response-cache-policy): Apigee returns the actual response from the target to the client and stores the entry in cache until it expires or is invalidated.\n- When a policy **updates** or **invalidates** an existing cache entry ([InvalidateCache policy](/apigee/docs/api-platform/reference/policies/invalidate-cache-policy), [PopulateCache policy](/apigee/docs/api-platform/reference/policies/populate-cache-policy), or [ResponseCache policy](/apigee/docs/api-platform/reference/policies/response-cache-policy)):\n 1. The message processor receiving the request deletes the entry from the one-second in-memory L1 cache and also deletes the entry from the L2 cache.\n 2. After an update or invalidation, it is possible that the other message processors will still hold onto the in-memory L1 cache.\n 3. Since L1 is configured to expire in one second, there is no delete/update event needed to remove the entry from L1.\n\nManaging cache limits\n---------------------\n\nThrough configuration, you can manage some aspects of the cache. The overall space\navailable for in-memory cache is limited by system resources and is not configurable.\nThe following constraints apply to cache:\n\n- **Cache limits** : [Various cache limits](/apigee/docs/api-platform/reference/limits) apply, such as name and value size, total number of caches, the number of items in a cache, and expiration.\n- **In-memory (L1) cache.** Memory limits for your cache are not configurable. Limits are set by Apigee for each message processor that hosts caches for multiple customers.\n\n In a hosted cloud environment, where in-memory caches for all customer deployments are hosted\n across multiple shared message processors, each processor features an Apigee-configurable\n memory percentage threshold to ensure that caching does not consume all of the application's\n memory. As the threshold is crossed for a given message processor, cache entries are evicted\n from memory on a least-recently-used basis. Entries evicted from memory remain in L2 cache\n until they expire or are invalidated.\n- **Persistent (L2) cache.** Entries evicted from the in-memory cache remain in the persistent cache according to configurable time-to-live settings.\n\nConfigurable optimizations\n--------------------------\n\nThe following table lists settings you can use to optimize cache performance."]]