Каталог можно не скачивать снова: проверяем ETag, If-None-Match и 304
Первый ответ 200 сохраняем вместе с ETag; на 304 повторно используем подходящий проверенный кэш и не ждём нового тела. Разбираем локальный тест, потерю кэша и безопасную обработку краёв.

В этой статье
Короткий ответ: 304 Not Modified означает, что сервер считает сохранённое представление пригодным для повторного использования по переданному валидатору. Нового тела каталога в таком ответе нет. Для слабого ETag это не доказательство побайтовой идентичности. Клиент должен использовать подходящий ранее проверенный ответ, сохранённый вместе с ETag для того же целевого URI, области данных, авторизации и варианта представления. Если кэш потерян или его происхождение неясно, импорт нужно остановить и получить полное представление способом, предусмотренным контрактом. Считать 304 пустой полной выгрузкой и деактивировать товары нельзя.
Практическая польза условного запроса проста: сохранённый ответ, который прошёл валидацию, не передаётся заново. Но экономия трафика здесь вторична. Главная задача — не перепутать отсутствие нового тела с новым пустым телом.
Что проверяют ETag и If-None-Match
ETag — валидатор выбранного представления ресурса. Клиент сохраняет его после успешного ответа и при следующем GET передаёт в заголовке If-None-Match. При совпадении по правилам слабого сравнения сервер может ответить 304 и разрешить повторное использование сохранённого ответа. Семантика описана в RFC 9110.
Ответ 304 не может содержать content или trailers. Поэтому обработчик не должен пытаться разобрать его как JSON. Нужный JSON уже лежит в проверенном кэше; сервер сообщил, что сохранённый ответ можно повторно использовать по правилам переданного валидатора.
Не путайте If-None-Match с If-Match. Первый удобен для проверки кэша при чтении. Второй разрешает изменение только при совпадении текущего ETag: если ресурс изменился после чтения, сервер отклоняет запрос и не даёт затереть более новую версию. Этот сценарий разобран отдельно в руководстве про ETag и If-Match.
Минимальный воспроизводимый пример
На маленьком примере поднимем HTTP-сервер только на локальном интерфейсе и свободном порту. Он отдаёт один товар, строит ETag как SHA-256 тела и выполняет три основные ветки плюс отдельную проверку 304 при потерянном кэше — всего четыре HTTP-обращения. Используется Python 3.12.14 и только стандартная библиотека. Создайте пустой временный каталог, сохраните следующий код в файл etag_catalog_lab.py и запускайте его из этого каталога; пример не обращается во внешнюю сеть, не изменяет рабочие данные и не удаляет файлы.
from __future__ import annotationsfrom hashlib import sha256from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom threading import Threadfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopenclass CatalogHandler(BaseHTTPRequestHandler): payload = b'{"products":[{"sku":"A","stock":7}]}' def do_GET(self) -> None: if self.path != "/catalog.json": self.send_error(404) return etag = '"' + sha256(self.payload).hexdigest() + '"' if self.headers.get("If-None-Match") == etag: self.send_response(304) self.send_header("ETag", etag) self.end_headers() return self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("ETag", etag) self.send_header("Content-Length", str(len(self.payload))) self.end_headers() self.wfile.write(self.payload) def log_message(self, format: str, *args: object) -> None: passdef fetch( url: str, previous_etag: str | None, cached_body: bytes | None) -> tuple[int, str, bytes, int]: headers = {"If-None-Match": previous_etag} if previous_etag else {} request = Request(url, headers=headers) try: with urlopen(request, timeout=2) as response: body = response.read() etag = response.headers["ETag"] return response.status, etag, body, len(body) except HTTPError as error: if error.code != 304 or previous_etag is None or cached_body is None: raise response_body = error.read() assert response_body == b"" return 304, error.headers["ETag"], cached_body, 0server = ThreadingHTTPServer(("127.0.0.1", 0), CatalogHandler)thread = Thread(target=server.serve_forever, daemon=True)thread.start()try: url = f"http://127.0.0.1:{server.server_port}/catalog.json" first_status, first_etag, first_body, first_bytes = fetch(url, None, None) assert first_status == 200 assert first_body == CatalogHandler.payload second_status, second_etag, second_body, second_bytes = fetch( url, first_etag, first_body ) assert second_status == 304 assert second_etag == first_etag assert second_body == first_body assert second_bytes == 0 missing_cache_blocked = False try: fetch(url, second_etag, None) except HTTPError as error: assert error.code == 304 missing_cache_blocked = True assert missing_cache_blocked CatalogHandler.payload = b'{"products":[{"sku":"A","stock":6}]}' third_status, third_etag, third_body, third_bytes = fetch( url, second_etag, second_body ) assert third_status == 200 assert third_etag != second_etag assert third_body == CatalogHandler.payload print( "first: " f"status={first_status} transferred={first_bytes} " f"etag_present={first_etag != ''}" ) print( "unchanged: " f"status={second_status} transferred={second_bytes} " f"cache_reused={second_body == first_body}" ) print( "missing_cache: " f"status=304 blocked={missing_cache_blocked}" ) print( "changed: " f"status={third_status} transferred={third_bytes} " f"etag_changed={third_etag != second_etag} stock=6" )finally: server.shutdown() server.server_close() thread.join(timeout=2)
python3 etag_catalog_lab.py
first: status=200 transferred=36 etag_present=Trueunchanged: status=304 transferred=0 cache_reused=Truemissing_cache: status=304 blocked=Truechanged: status=200 transferred=36 etag_changed=True stock=6
Сценарий выполнен два раза подряд, оба запуска завершились с кодом 0 и одинаковым выводом.
Запрос | Условие | Статус | Передано | Действие клиента |
|---|---|---|---|---|
Первый | Кэша нет | 200 | 36 байт | Проверить и сохранить тело с ETag A |
Второй | If-None-Match: A | 304 | 0 байт | Повторно использовать проверенный кэш |
Третий | Тело изменилось, клиент прислал A | 200 | 36 байт | Проверить новое тело и сохранить ETag B |

Что именно доказал тест
- Первый ответ 200 действительно содержит 36 байт JSON и ETag.
- Повтор с тем же сильным ETag в учебном сервере получает 304 без тела, а клиент возвращает ранее сохранённые байты.
- Отдельный запрос с тем же ETag, но без сохранённого тела, получает 304 и блокируется клиентом.
- После изменения stock с 7 на 6 ETag меняется, и сервер снова отдаёт 200 с полным телом.
Тест не доказывает производительность и не воспроизводит конкретный модуль 1С-Битрикс или API поставщика. Это локальная модель HTTP-контракта. Учебный сервер намеренно поддерживает один точный сильный ETag и показывает ветвление клиента; это не готовый парсер полной грамматики If-None-Match со списком тегов, W/ и *. В реальной интеграции источник может не отдавать ETag вообще или формировать его по своим правилам.
Алгоритм клиента в рабочем контуре
Первый ответ 200 проверить до импорта: статус, Content-Type, структуру JSON, признак полного либо частичного снимка, границы включённых данных и обязательные поля. Затем атомарно сохранить проверенные байты, ETag и ключ представления.
В следующем GET передать сохранённый ETag в If-None-Match только для того же ключа представления.
На 304 сопоставить ответ с правильной записью кэша, сохранить прежнее тело и обновить разрешённые метаданные ответа. Не заменять тело пустотой и не запускать операции, которые требуют нового полного снимка.
На 200 сначала проверить новое тело. Только после успешной проверки заменить кэш и передать данные в импорт.
Ошибку, перенаправление, отказ авторизации или неожиданный тип ответа обрабатывать отдельно. Они не подтверждают, что каталог остался без изменений, и не подтверждают, что каталог пуст.
Ключ представления стоит сделать явным. Минимум в него входят целевой URI, идентификатор поставщика или арендатора, область каталога, контекст авторизации — арендатор, пользователь и набор прав без сохранения токена или секрета — и заголовки, перечисленные сервером в Vary. Один и тот же ETag нельзя переносить между разными ключами.
При выборе сохранённого ответа нужно учитывать Vary, а после успешного 304 — обновлять метаданные кэша по правилам HTTP. Эти требования описаны в RFC 9111: выбор ответа по Vary — в разделе 4.1, обновление после валидации — в разделе 4.3.4.
Крайние случаи, которые нельзя прятать
- ETag отсутствует. Не придумывайте его на стороне клиента и не считайте ответ пригодным для повторного использования; применяйте только документированный запасной механизм источника.
- Пришёл 304, а кэш утрачен. Это блокирующее состояние: импорт не запускается, пока клиент не получит и не проверит полное представление.
- Изменились URI, авторизация, язык, формат, границы включённых данных или влияющий на вариант заголовок Vary. Старый ETag и старое тело не принадлежат новому ключу кэша.
- Пришёл слабый ETag с префиксом W/. Для If-None-Match слабое сравнение допустимо; удалять префикс или преобразовывать тег не нужно. Слабое совпадение разрешает повторное использование, но не доказывает равенство байтов.
- Прокси удаляет ETag или If-None-Match. Сначала подтвердите фактические заголовки на тестовом контуре; статус 200 сам по себе не показывает причину.
- Сильный ETag остался прежним при изменившихся байтах. Это дефект контракта или реализации источника; клиент не может надёжно обнаружить изменение по этому валидатору.
- Пришёл 200 с пустым списком. Это новое тело ответа, но оно всё равно не разрешает деактивацию, пока не подтверждены полный снимок, точные границы включённых данных и успешное завершение всех страниц.
Тут есть подвох: успешная валидация подтверждает пригодность сохранённого ответа по правилам валидатора. Она не подтверждает бизнес-полноту и, для слабого ETag, побайтовую идентичность. Если поставщик по ошибке построил неполный снимок и присвоил ему тег, условный запрос эту ошибку не исправит. Нужны отдельные проверки полноты и области данных.
Граница с 1С-Битрикс и деактивацией товаров
В 1С-Битрикс: Управление сайтом этот алгоритм относится к собственному адаптеру, модулю обмена или внешнему сервису, только если его HTTP-контракт действительно поддерживает ETag. Наличие стандарта HTTP не доказывает поддержку конкретным поставщиком. До внедрения нужно определить и документировать направление обмена, режим полного снимка или дельта-выгрузки, состав торговых предложений и поля, входящие в представление.
Ответ 304 не содержит нового списка товаров, поэтому он не может быть основанием для деактивации отсутствующих позиций. Условие безопасной деактивации — завершённый полный снимок с проверенной областью; границы этого решения разобраны в материале «Товар пропал из выгрузки 1С».
Отдельно проверьте единицу сравнения. Товар и торговое предложение — разные сущности. Если API возвращает предложения по отдельному фильтру, ETag карточки товара не подтверждает, что остатки и цены всех предложений остались прежними.
Как принять реализацию
- Первый 200 сохраняет проверенное тело и точный ETag одним согласованным действием.
- Повтор с подходящим валидатором получает 304 и не передаёт новое тело.
- На 304 клиент сопоставляет правильную запись кэша, сохраняет прежнее тело и обновляет разрешённые метаданные ответа.
- 304 без кэша останавливает импорт и не меняет каталог.
- После изменения тестовых данных приходит 200, новый ETag и новое проверенное тело.
- Ошибки и неожиданные ответы не перезаписывают последний валидный кэш.
- Ни одна ветка 304 не запускает деактивацию товаров или торговых предложений.
- В журнале интеграции различимы статус ответа, ключ представления, факт использования кэша и результат проверки тела, но само содержимое каталога и секреты не выводятся.
Критерий результата здесь не «запрос стал быстрее». Он точнее: после успешной валидации сеть не передаёт новое тело, клиент повторно использует подходящий проверенный ответ, а любое сомнение в происхождении кэша останавливает импорт до получения полного ответа.
Short answer: 304 Not Modified means the server considers the stored representation suitable for reuse based on the provided validator. There is no new catalog body in such a response. For a weak ETag, this is not proof of byte-for-byte identity. The client must use a previously validated response suitable for the same target URI, data scope, authorization, and representation variant, which was saved along with the ETag. If the cache is lost or its origin is unclear, the import must be stopped and the full representation obtained via the method prescribed by the contract. A 304 cannot be treated as an empty full export, nor can products be deactivated.
The practical benefit of a conditional request is simple: a stored response that has passed validation is not sent again. However, bandwidth savings are secondary here. The main task is not to confuse the absence of a new body with a new empty body.
What ETag and If-None-Match check
An ETag is a validator for a selected resource representation. The client saves it after a successful response and sends it in the If-None-Match header on the next GET request. If they match according to weak comparison rules, the server may respond with 304 and allow reuse of the saved response. The semantics are described in RFC 9110.
A 304 response cannot contain a body or trailers. Therefore, the handler must not attempt to parse it as JSON. The required JSON is already in the validated cache; the server indicated that the cached response can be reused according to the rules of the provided validator.
Do not confuse If-None-Match with If-Match. The former is convenient for cache validation during reads. The latter allows modification only if the current ETag matches: if the resource has changed since the read, the server rejects the request and prevents overwriting a newer version. This scenario is covered separately in the guide on ETag and If-Match.
Minimal reproducible example
On a small example, we start an HTTP server only on the local interface and a free port. It serves one product, builds an ETag as the SHA-256 hash of the body, and executes three main branches plus a separate 304 check for a lost cache—four HTTP requests in total. Python 3.12.14 and only the standard library are used. Create an empty temporary directory, save the following code to a file named etag_catalog_lab.py, and run it from that directory; the example does not access external networks, does not modify working data, and does not delete files.
from __future__ import annotationsfrom hashlib import sha256from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom threading import Threadfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopenclass CatalogHandler(BaseHTTPRequestHandler): payload = b'{"products":[{"sku":"A","stock":7}]}' def do_GET(self) -> None: if self.path != "/catalog.json": self.send_error(404) return etag = '"' + sha256(self.payload).hexdigest() + '"' if self.headers.get("If-None-Match") == etag: self.send_response(304) self.send_header("ETag", etag) self.end_headers() return self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("ETag", etag) self.send_header("Content-Length", str(len(self.payload))) self.end_headers() self.wfile.write(self.payload) def log_message(self, format: str, *args: object) -> None: passdef fetch( url: str, previous_etag: str | None, cached_body: bytes | None) -> tuple[int, str, bytes, int]: headers = {"If-None-Match": previous_etag} if previous_etag else {} request = Request(url, headers=headers) try: with urlopen(request, timeout=2) as response: body = response.read() etag = response.headers["ETag"] return response.status, etag, body, len(body) except HTTPError as error: if error.code != 304 or previous_etag is None or cached_body is None: raise response_body = error.read() assert response_body == b"" return 304, error.headers["ETag"], cached_body, 0server = ThreadingHTTPServer(("127.0.0.1", 0), CatalogHandler)thread = Thread(target=server.serve_forever, daemon=True)thread.start()try: url = f"http://127.0.0.1:{server.server_port}/catalog.json" first_status, first_etag, first_body, first_bytes = fetch(url, None, None) assert first_status == 200 assert first_body == CatalogHandler.payload second_status, second_etag, second_body, second_bytes = fetch( url, first_etag, first_body ) assert second_status == 304 assert second_etag == first_etag assert second_body == first_body assert second_bytes == 0 missing_cache_blocked = False try: fetch(url, second_etag, None) except HTTPError as error: assert error.code == 304 missing_cache_blocked = True assert missing_cache_blocked CatalogHandler.payload = b'{"products":[{"sku":"A","stock":6}]}' third_status, third_etag, third_body, third_bytes = fetch( url, second_etag, second_body ) assert third_status == 200 assert third_etag != second_etag assert third_body == CatalogHandler.payload print( "first: " f"status={first_status} transferred={first_bytes} " f"etag_present={first_etag != ''}" ) print( "unchanged: " f"status={second_status} transferred={second_bytes} " f"cache_reused={second_body == first_body}" ) print( "missing_cache: " f"status=304 blocked={missing_cache_blocked}" ) print( "changed: " f"status={third_status} transferred={third_bytes} " f"etag_changed={third_etag != second_etag} stock=6" )finally: server.shutdown() server.server_close() thread.join(timeout=2)
python3 etag_catalog_lab.py
first: status=200 transferred=36 etag_present=Trueunchanged: status=304 transferred=0 cache_reused=Truemissing_cache: status=304 blocked=Truechanged: status=200 transferred=36 etag_changed=True stock=6
The scenario was executed twice in a row; both runs completed with exit code 0 and identical output.
Request | Condition | Status | Transferred | Client action |
|---|---|---|---|---|
First | No cache | 200 | 36 bytes | Check and save the body with ETag A |
Second | If-None-Match: A | 304 | 0 bytes | Reuse the verified cache |
Third | The body changed; the client sent A | 200 | 36 bytes | Verify the new body and save ETag B |

What exactly the test proved
- The initial 200 response indeed contains 36 bytes of JSON and an ETag.
- A subsequent request with the same strong ETag on the test server receives a 304 without a body, and the client returns the previously saved bytes.
- A separate request with the same ETag but without a saved body receives a 304 and is blocked by the client.
- After changing stock from 7 to 6, the ETag changes, and the server again returns a 200 with the full body.
This test does not prove performance nor reproduce a specific 1C-Bitrix module or supplier API. It is a local model of the HTTP contract. The test server intentionally supports exactly one strong ETag and demonstrates client branching; it is not a ready-made parser for the full grammar of If-None-Match with a list of tags, W/ prefixes, and *. In a real integration, the source may not return an ETag at all or may generate it according to its own rules.
Client algorithm in a production environment
Verify the first 200 response before import: status, Content-Type, JSON structure, full or partial snapshot flag, data inclusion boundaries, and required fields. Then atomically save the verified bytes, ETag, and representation key.
In the subsequent GET, pass the saved ETag in If-None-Match only for the same representation key.
On 304, match the response to the correct cache entry, retain the original body, and update allowed response metadata. Do not replace the body with an empty value or trigger operations that require a new full snapshot.
First, verify the new body on a 200 response. Only after a successful verification should you replace the cache and pass the data to the import.
Handle errors, redirects, authorization failures, or unexpected response types separately. These do not confirm that the catalog remains unchanged, nor do they confirm that the catalog is empty.
The representation key should be made explicit. At minimum, it must include the target URI, supplier or tenant identifier, catalog scope, authorization context—tenant, user, and a set of permissions without saving the token or secret—and headers listed by the server in Vary. The same ETag cannot be transferred between different keys.
When selecting a cached response, consider the Vary header; after a successful 304, update the cache metadata according to HTTP rules. These requirements are described in RFC 9111: selecting a response based on Vary in section 4.1, and updating after validation in section 4.3.4.
Edge cases that must not be ignored
- ETag is missing. Do not invent one on the client side or consider the response reusable; use only the documented fallback mechanism of the source.
- A 304 response arrives, but the cache is lost. This is a blocking state: the import does not start until the client receives and validates the full representation.
- URI, authorization, language, format, included data boundaries, or a Vary header affecting the variant have changed. The old ETag and old body do not belong to the new cache key.
- A weak ETag with the W/ prefix arrives. Weak comparison is allowed for If-None-Match; do not remove the prefix or convert the tag. A weak match permits reuse but does not prove byte equality.
- The proxy removes the ETag or If-None-Match. First, verify the actual headers on the staging environment; a 200 status alone does not reveal the cause.
- A strong ETag remains unchanged despite different bytes. This is a defect in the source contract or implementation; the client cannot reliably detect the change using this validator.
- A 200 response arrives with an empty list. This is a new response body, but it still does not allow deactivation until the full snapshot, exact included data boundaries, and successful completion of all pages are confirmed.
There is a catch: successful validation confirms that the cached response meets the validator's rules. It does not confirm business completeness, nor byte-for-byte identity for weak ETags. If a provider erroneously constructs an incomplete snapshot and assigns it a tag, a conditional request will not correct that error. Separate checks for completeness and data scope are required.
Boundary with 1C-Bitrix and product deactivation
In 1C-Bitrix: Site Management, this algorithm applies to a custom adapter, exchange module, or external service only if its HTTP contract truly supports ETag. The existence of an HTTP standard does not prove that a specific provider supports it. Before implementation, you must define and document the exchange direction, the mode of full snapshot or delta export, the set of product variants, and the fields included in the representation.
A 304 response does not contain a new list of products, so it cannot serve as a basis for deactivating missing items. The condition for safe deactivation is a completed full snapshot with a verified scope; the boundaries of this solution are discussed in the article 'Product Disappeared from 1C Export'.
Separately verify the unit of comparison. A product and a product variant are distinct entities. If the API returns variants via a separate filter, the ETag of the product card does not confirm that stock levels and prices for all variants remain unchanged.
How to accept the implementation
- The first 200 response saves the verified body and exact ETag in a single atomic action.
- A repeat request with a matching validator receives a 304 and does not transmit a new body.
- On a 304, the client maps the correct cache entry, retains the previous body, and updates the allowed response metadata.
- A 304 without a cache stops the import and does not modify the catalog.
- After test data changes, a 200 response arrives with a new ETag and a new verified body.
- Errors and unexpected responses do not overwrite the last valid cache.
- No 304 branch triggers product or product variant deactivation.
- The integration log distinguishes the response status, representation key, cache usage fact, and body verification result, but does not output the actual catalog content or secrets.
The result criterion here is not "the request became faster." It is more precise: after successful validation, the network does not transmit a new body, the client reuses a suitable verified response, and any doubt about the cache origin stops the import until a full response is received.





Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.