---
# === IDENTITY ===
id: business/erp-integration/sap-idoc-edi-integration/2026
canonical_question: "What are SAP IDocs - message types, basic types, segments, and EDI integration capabilities?"
aliases:
  - "How do SAP IDocs work for EDI integration?"
  - "What is the difference between IDoc message types and basic types?"
  - "How to configure SAP IDoc partner profiles and ports for EDI?"
  - "What are common SAP IDoc types like ORDERS05, INVOIC02, MATMAS?"
entity_type: erp_integration
domain: business > erp-integration > SAP IDoc EDI Integration
region: global
jurisdiction: global
temporal_scope: 2024-2026

# === SYSTEM PROFILE ===
systems:
  - name: "SAP S/4HANA"
    vendor: "SAP"
    version: "2408"
    edition: "All editions (on-premise, private cloud, public cloud)"
    deployment: "cloud/on-premise/hybrid"
    api_surface: "IDoc/EDI"

# === VERIFICATION ===
last_verified: 2026-03-01
confidence: 0.92
version: 1.0
first_published: 2026-03-01

# === TEMPORAL VALIDITY ===
temporal_validity:
  status: evolving
  last_breaking_change: "S/4HANA 2020 — new segments in INVOIC02 and MATMAS IDocs"
  next_review: 2026-08-28
  change_sensitivity: medium

# === CONSTRAINTS ===
constraints:
  - "S/4HANA Cloud Public Edition does NOT support IDoc/ALE — use OData or SOAP APIs instead"
  - "IDoc processing is always asynchronous — no synchronous request/response pattern available"
  - "Maximum IDoc size is limited by dialog work process timeout (default 600s) and memory (default 2GB roll area)"
  - "Partner profiles must be configured per message type AND per partner — no wildcard routing"
  - "Custom IDoc extensions must use Z-prefix naming convention for segments and types"
  - "Outbound IDocs require explicit output determination or ALE distribution model configuration"

# === SKIP CONDITIONS ===
skip_this_unit_if:
  - condition: "User needs real-time synchronous API integration with SAP"
    use_instead: "business/erp-integration/sap-s4hana-odata-api/2026"
  - condition: "User is on S/4HANA Cloud Public Edition (multi-tenant)"
    use_instead: "business/erp-integration/sap-s4hana-cloud-api/2026"
  - condition: "User needs SAP-to-SAP data replication only"
    use_instead: "business/erp-integration/sap-slt-cds-replication/2026"

# === AGENT HINTS ===
inputs_needed:
  - key: integration_pattern
    question: "What integration pattern do you need?"
    type: choice
    options:
      - "EDI with external trading partners (X12/EDIFACT)"
      - "ALE distribution between SAP systems"
      - "middleware-mediated integration (MuleSoft, Boomi, BTP)"
      - "file-based batch exchange"
  - key: data_volume
    question: "What's your daily IDoc volume?"
    type: choice
    options:
      - "< 1,000 IDocs/day"
      - "1,000-50,000 IDocs/day"
      - "> 50,000 IDocs/day"
  - key: direction
    question: "What's the data flow direction?"
    type: choice
    options:
      - "inbound (receiving IDocs into SAP)"
      - "outbound (sending IDocs from SAP)"
      - "bidirectional"

# === DISTRIBUTION ===
canonical_source: "https://knowledgelib.io/business/erp-integration/sap-idoc-edi-integration/2026"
suggested_citation: "Source: knowledgelib.io — AI Knowledge Library (verified 2026-03-01)"

# === RELATED UNITS ===
related_kos:
  depends_on: []
  related_to:
    - id: "business/erp-integration/sap-s4hana-odata-api/2026"
      label: "SAP S/4HANA OData API — synchronous alternative to IDocs"
  solves: []
  alternative_to:
    - id: "business/erp-integration/sap-s4hana-cloud-api/2026"
      label: "SAP S/4HANA Cloud API — for public cloud edition (no IDoc support)"
  often_confused_with:
    - id: "business/erp-integration/sap-bapi-rfc-integration/2026"
      label: "SAP BAPI/RFC — synchronous function calls vs asynchronous IDocs"

# === SOURCES ===
sources:
  - id: src1
    title: "IDoc Basics Explained — IDoc Basic Type and IDoc Message Type"
    author: ecosio
    url: https://ecosio.com/en/blog/idoc-basics-idoc-basic-type-and-idoc-message-type/
    type: technical_blog
    published: 2024-06-15
    reliability: high
  - id: src2
    title: "EDI_DC40: Understand the SAP IDoc Control Record"
    author: ecosio
    url: https://ecosio.com/en/blog/edi_dc40-understand-the-sap-idoc-control-record/
    type: technical_blog
    published: 2024-03-20
    reliability: high
  - id: src3
    title: "Reprocessing IDocs in SAP ERP Systems"
    author: ecosio
    url: https://ecosio.com/en/blog/reprocessing-idocs-in-sap-erp/
    type: technical_blog
    published: 2024-08-10
    reliability: high
  - id: src4
    title: "IDocs in SAP S/4HANA: The Differences to SAP ECC 6.0"
    author: ecosio
    url: https://ecosio.com/en/blog/idocs-in-s4hana/
    type: technical_blog
    published: 2024-11-05
    reliability: high
  - id: src5
    title: "SAP IDoc Tutorial: Definition, Structure, Types, Format & Tables"
    author: Guru99
    url: https://www.guru99.com/all-about-idocdefinition-architecture-implementation.html
    type: community_resource
    published: 2024-01-15
    reliability: moderate_high
  - id: src6
    title: "How to Configure EDI Interfaces with MM in SAP S/4HANA"
    author: SAP Press
    url: https://blog.sap-press.com/configure-edi-interfaces-with-mm-in-sap-s4hana
    type: technical_blog
    published: 2024-05-20
    reliability: high
  - id: src7
    title: "SAP IDoc Standard — Message Types List"
    author: CData Arc
    url: https://arc.cdata.com/edi/standards/sap/
    type: technical_blog
    published: 2025-01-10
    reliability: moderate_high
  - id: src8
    title: "Connection of SAP S/4HANA to EDI solution via API instead of IDoc"
    author: SEEBURGER
    url: https://blog.seeburger.com/edi-connection-sap-s4hana-with-apis-instead-of-idocs/
    type: technical_blog
    published: 2025-02-15
    reliability: high
---

# SAP IDocs and EDI Integration

## TL;DR

- **Bottom line**: IDocs (Intermediate Documents) are SAP's native asynchronous document format for B2B EDI and system-to-system data exchange; they remain the standard integration format in S/4HANA on-premise and private cloud, but are NOT available in S/4HANA Cloud Public Edition.
- **Key limit**: IDoc processing is always asynchronous -- no synchronous request/response; partner profiles must be configured per message type per partner with no wildcard routing.
- **Watch out for**: S/4HANA Cloud Public Edition does not support IDocs or ALE at all -- agents must check the deployment model before recommending IDoc-based integration.
- **Best for**: High-volume B2B EDI with trading partners (orders, invoices, ASNs, master data distribution) and ALE-based SAP-to-SAP distribution.
- **Authentication**: IDocs use SAP's trusted RFC connections (partner profiles + logical systems) or file-based ports -- no OAuth/API key mechanism.

## System Profile

SAP IDocs are the native document exchange format used across all SAP ERP systems since R/3. In S/4HANA (release 2408), IDocs remain fully supported for on-premise and private cloud deployments. The IDoc framework handles both EDI (Electronic Data Interchange) with external trading partners via X12/EDIFACT translation and ALE (Application Link Enabling) for SAP-to-SAP distribution. S/4HANA Cloud Public Edition (multi-tenant) does NOT support IDocs -- use OData or SOAP APIs instead. [src4, src8]

| Property | Value |
|---|---|
| **Vendor** | SAP |
| **System** | SAP S/4HANA 2408 |
| **API Surface** | IDoc / EDI / ALE |
| **Current Version** | IDoc release 7.40+ (S/4HANA 2408) |
| **Editions Covered** | On-Premise, Private Cloud (RISE), ECC 6.0 (legacy) |
| **Deployment** | On-Premise / Private Cloud / Hybrid |
| **API Docs URL** | [SAP Help — IDoc Interface](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/latest) |
| **Status** | GA (stable, actively maintained) |

## API Surfaces & Capabilities

IDocs are not a traditional REST/SOAP API but a document-based asynchronous messaging system. The IDoc framework provides multiple "surfaces" for exchanging data. [src1, src5]

| API Surface | Protocol | Best For | Max Records/Request | Rate Limit | Real-time? | Bulk? |
|---|---|---|---|---|---|---|
| IDoc via tRFC | Transactional RFC | ALE distribution between SAP systems | Unlimited (1 IDoc = 1 document) | Work process dependent | Near real-time | Yes (packet mode) |
| IDoc via File Port | Flat file / XML | EDI subsystem integration (Seeburger, OpenText) | File size limited by OS | N/A (file system) | No (batch) | Yes |
| IDoc via HTTP Port | HTTPS/XML | Cloud middleware (BTP, MuleSoft, Boomi) | 1 IDoc per HTTP POST | Server-dependent | Near real-time | No |
| IDoc via XML Port | XML/RFC | XML-based integration with SOA middleware | 1 IDoc per call | Work process dependent | Near real-time | No |
| ALE Distribution | tRFC + IDoc | Master data distribution across SAP landscape | Configurable packet size | Work process dependent | Near real-time | Yes |

## Rate Limits & Quotas

IDocs do not have traditional API rate limits. Instead, throughput is constrained by SAP system resources: dialog/background work processes, database I/O, and RFC connection pools. [src5, src6]

### Per-Request Limits

| Limit Type | Value | Applies To | Notes |
|---|---|---|---|
| Max IDoc size | ~2 GB (roll area limit) | Single IDoc | Practical limit is ~100K segments per IDoc |
| Max segments per IDoc | 999,999 (theoretical) | Data records | Rarely exceeds 10,000 in practice |
| Max segment data length | 1,000 bytes | Single segment (SDATA field) | Fixed-width character format |
| Control record fields | 524 bytes | EDI_DC40 structure | Includes sender, receiver, message type, IDoc type |
| Max packet size (ALE) | Configurable (default 1) | Outbound dispatch | Set in partner profile; increase to 50-200 for bulk |

### Rolling / Daily Limits

| Limit Type | Value | Window | Edition Differences |
|---|---|---|---|
| Dialog work process timeout | 600 seconds (default) | Per process | Configurable via rdisp/max_wprun_time |
| Background job timeout | 86,400 seconds (24h) | Per job | Configurable; no hard SAP limit |
| RFC connections | 100 (default) | Per destination | Set in SM59; increase for high-volume |
| Parallel IDoc processing | 1-20 work processes | Concurrent | Set via RBDAPP01 parallelization parameter |

### Transaction / Governor Limits

| Limit Type | Per-Transaction Value | Notes |
|---|---|---|
| Dialog step timeout | 600s default | Configurable via profile parameter; exceeding aborts IDoc processing |
| Memory per work process | 2 GB (64-bit) | Extended memory + roll area; large IDocs can exhaust this |
| Database locks | Table-dependent | MATMAS IDocs on same material can deadlock if processed in parallel |
| Commit frequency | Every N IDocs (configurable) | RBDAPP01 parameter PACKET_SIZE; default 1; set to 50-100 for throughput |

## Authentication

IDocs use SAP's internal authentication mechanisms rather than external API keys or OAuth. Authentication is configured through partner profiles, logical systems, and RFC destinations. [src5, src6]

| Flow | Use When | Token Lifetime | Refresh? | Notes |
|---|---|---|---|---|
| Trusted RFC (SM59) | SAP-to-SAP ALE distribution | Session-based | Auto-refresh | Requires trust relationship between systems |
| Standard RFC (SM59) | Middleware integration via tRFC port | Session-based | Auto-refresh | Stored credentials in RFC destination |
| File port (WE21) | EDI subsystem reads/writes files | N/A (filesystem) | N/A | OS-level file permissions control access |
| HTTP port (WE21) | Cloud middleware via HTTPS | Certificate-based | N/A | Mutual TLS recommended for production |
| X.509 certificate | SNC-encrypted RFC connections | Certificate validity | Annual renewal | Required for production cross-system communication |

### Authentication Gotchas

- Trusted RFC connections require bidirectional trust configuration -- setting trust on system A for system B does NOT automatically grant system B trust on system A. [src5]
- File ports use the SAP application server's OS user -- ensure the `<sid>adm` user has read/write permissions on the IDoc file directory, not just the logged-in user. [src6]
- HTTP port authentication is configured separately from RFC -- an RFC user with full IDoc access does NOT automatically have HTTP port access. [src6]

## Constraints
<!-- Agents: read this section before recommending any integration approach from this unit.
     These are hard constraints that must not be violated. -->

- **S/4HANA Cloud Public Edition exclusion**: IDoc and ALE technologies are NOT available on the multi-tenant cloud edition. This is the #1 constraint agents get wrong. [src8]
- **Asynchronous only**: IDoc processing is always asynchronous. There is no mechanism to get a synchronous response from IDoc processing -- use BAPI/RFC if you need immediate confirmation. [src1]
- **Partner profile required**: Every IDoc exchange requires a partner profile (WE20) with message type, process code, and port configured. No default/wildcard routing exists. [src6]
- **Extension naming**: Custom IDoc extensions MUST use Z-prefix for segment names (e.g., Z1MYSEG). SAP will reject segments without proper namespace. [src4]
- **EDI subsystem dependency**: IDoc-to-X12/EDIFACT translation requires an external EDI subsystem (Seeburger BIS, OpenText B2B, SAP Integration Suite). SAP does NOT natively translate IDocs to EDI standards. [src6]
- **Serialization constraints**: IDocs with serialization (status 66) block processing of dependent IDocs until the predecessor completes. Misconfigured serialization can halt entire message type processing. [src3]

## Integration Pattern Decision Tree

```
START -- User needs IDoc/EDI integration with SAP
|-- What's the deployment model?
|   |-- S/4HANA Cloud Public Edition?
|   |   |-- YES --> STOP. IDocs not available. Use OData/SOAP APIs.
|   |   +-- NO --> Continue
|   +-- On-Premise / Private Cloud / ECC?
|       +-- Continue below
|-- What's the integration pattern?
|   |-- EDI with external trading partners (X12/EDIFACT)
|   |   |-- Need real-time? --> tRFC port to EDI subsystem (Seeburger, OpenText)
|   |   +-- Batch acceptable? --> File port + scheduled EDI translation
|   |-- ALE distribution (SAP-to-SAP)
|   |   |-- Master data replication? --> MATMAS/DEBMAS/CREAMS via BD64 model
|   |   |-- Transactional data? --> ORDERS/INVOIC/DESADV via output determination
|   |   +-- Need filtering? --> ALE distribution model with filters (BD64)
|   |-- Middleware integration (MuleSoft, Boomi, BTP)
|   |   |-- Cloud middleware? --> HTTP/XML port (WE21)
|   |   |-- On-premise middleware? --> tRFC port or file port
|   |   +-- SAP BTP? --> Cloud Connector + RFC or IDoc adapter
|   +-- File-based batch
|       +-- File port (WE21) + OS-level file transfer (SFTP/SCP)
|-- Which direction?
|   |-- Inbound (into SAP) --> Configure process code + partner profile inbound params
|   |-- Outbound (from SAP) --> Configure output determination OR ALE distribution model
|   +-- Bidirectional --> Configure BOTH; use change pointers for master data sync
+-- Error tolerance?
    |-- Zero-loss required --> Enable IDoc serialization + monitoring via BD87
    +-- Best-effort --> Standard IDoc processing with alerting on status 51/56
```

## Quick Reference

### Core IDoc Architecture

| Component | Description | SAP Table | Transaction |
|---|---|---|---|
| Control Record | Metadata: sender, receiver, message type, IDoc type, status | EDIDC (EDI_DC40 structure) | WE02, WE05 |
| Data Records | Business payload organized in hierarchical segments | EDID4 | WE02 |
| Status Records | Processing history with timestamps and status codes | EDIDS | WE02 |
| Message Type | Logical business document intent (e.g., ORDERS, INVOIC) | EDIMSG | WE81 |
| Basic Type | Physical IDoc structure and segment layout (e.g., ORDERS05) | EDBAS, EDBAST | WE30 |
| Extension Type | Custom additions to standard basic types (Z-prefix) | EDIDC.CIMTYPE field | WE30 |
| Segment | Reusable data structure within an IDoc (e.g., E1EDK01) | EDISDEF | WE31 |
| Partner Profile | Per-partner, per-message-type routing and processing rules | EDPP1 | WE20 |
| Port | Communication channel (tRFC, file, HTTP, XML) | EDIPORT | WE21 |
| Process Code | Links inbound IDoc to function module for posting | EDIPOA | WE42 |
| Distribution Model | ALE routing rules: which message types flow between which systems | TBD* | BD64 |

### Common IDoc Message Types and Basic Types [src7]

| Message Type | Basic Type | Business Document | Direction | SAP Module |
|---|---|---|---|---|
| ORDERS | ORDERS05 | Purchase Order / Sales Order | Inbound/Outbound | MM/SD |
| INVOIC | INVOIC02 | Invoice (AR/AP) | Inbound/Outbound | FI/MM |
| DESADV | DELVRY05 | Advance Shipping Notification (ASN) | Outbound | SD/LE |
| MATMAS | MATMAS05 | Material Master | Outbound (ALE) | MM |
| DEBMAS | DEBMAS07 | Customer Master | Outbound (ALE) | SD |
| CREMAS | CREMAS07 | Vendor Master | Outbound (ALE) | MM |
| WMMBID | WMMBID02 | Goods Movement | Inbound | WM |
| SHPMNT | SHPMNT05 | Shipment | Outbound | LE |
| HRMD_A | HRMD_A07 | HR Master Data | Outbound (ALE) | HR |
| PAYEXT | PEXR2002 | Payment Order | Outbound | FI |
| FIDCCP | FIDCCP02 | Accounting Document | Outbound | FI |

### Key Transaction Codes [src3, src5, src6]

| Transaction | Purpose | When to Use |
|---|---|---|
| WE02 / WE05 | Display IDoc list | Monitor IDoc processing status |
| WE19 | IDoc test tool | Test inbound processing with modified data |
| WE20 | Partner profiles | Configure per-partner IDoc routing |
| WE21 | Port definition | Define tRFC, file, HTTP, or XML ports |
| WE30 | IDoc type development | View/create basic types and extensions |
| WE31 | Segment definition | Create custom Z-segments for extensions |
| WE42 | Inbound process codes | Map message types to posting function modules |
| WE41 | Outbound process codes | Map message types to outbound function modules |
| WE81 | Message type assignment | Assign message types to basic types |
| BD64 | ALE distribution model | Define which IDocs flow between logical systems |
| BD87 | IDoc reprocessing | Filter, edit, and reprocess failed IDocs |
| BD20 | Process inbound IDocs | Reprocess IDocs in status 64 or 66 |
| BD83 | Reprocess outbound IDocs | Reprocess IDocs in status 02, 04, 05, 25, 29 |
| SM59 | RFC destinations | Configure communication channels between systems |
| SALE | ALE configuration | Central ALE customizing menu |

## Step-by-Step Integration Guide

### 1. Define logical systems and assign to client (SALE/BD54)

Create logical systems for the sender and receiver in transaction SALE > Basic Settings > Logical Systems. Assign the local logical system to the client. This establishes the identity of each system in the ALE framework. [src5, src6]

```
Transaction: SALE
Path: Basic Settings > Logical Systems > Define Logical System
  - Create: CLNT100 (local SAP system)
  - Create: EDISUB01 (EDI subsystem)

Transaction: SALE
Path: Basic Settings > Logical Systems > Assign Logical System to Client
  - Client 100 --> CLNT100
```

**Verify**: `Transaction SCC4` --> Check that client 100 shows logical system CLNT100.

### 2. Define ports for IDoc communication (WE21)

Create a port that defines HOW IDocs are transmitted. For EDI subsystem integration, use a file port or tRFC port. For cloud middleware, use an HTTP port. [src6]

```
Transaction: WE21

File Port (for EDI subsystem):
  - Port: EDIPORT1
  - Description: EDI Subsystem File Port
  - Function module: EDI_PATH_CREATE_CLIENT_DOCNUM (generates unique filenames)
  - Outbound directory: /usr/sap/<SID>/edi/outbound/
  - Inbound directory: /usr/sap/<SID>/edi/inbound/

tRFC Port (for ALE):
  - Port: TRFC01
  - Description: ALE tRFC Port
  - RFC destination: EDISUB01 (from SM59)
  - Version: IDoc record types SAP Release 4.x
```

**Verify**: `Transaction WE21` --> Port EDIPORT1 shows green status. Test with "Test outbound processing."

### 3. Create partner profiles (WE20)

Define WHO sends/receives IDocs and WHAT message types are exchanged. Every partner-message type combination needs explicit configuration. [src6]

```
Transaction: WE20

Partner Number: EDISUB01
Partner Type: LS (Logical System)

Outbound Parameters:
  - Message Type: ORDERS
  - Receiver Port: EDIPORT1
  - Basic Type: ORDERS05
  - Output Mode: Transfer IDoc immediately (or Collect IDocs)
  - Pack Size: 1 (increase to 50-100 for high-volume)

Inbound Parameters:
  - Message Type: INVOIC
  - Process Code: INVL (or custom process code)
  - Triggering Event: Immediate processing (or background)
```

**Verify**: `Transaction WE20` --> Partner EDISUB01 shows both inbound and outbound parameters with green checks.

### 4. Configure ALE distribution model (BD64)

For master data distribution, create a distribution model that defines the flow of message types between logical systems. [src5]

```
Transaction: BD64

1. Switch to Edit mode
2. Create Model View: ZEDIMODEL "EDI Integration Model"
3. Add Message Type:
   - Sender: CLNT100
   - Receiver: EDISUB01
   - Message Type: ORDERS
4. Repeat for each message type (INVOIC, DESADV, MATMAS, etc.)
5. Save and distribute model (Environment > Generate Partner Profiles)
```

**Verify**: `Transaction BD64` --> Model ZEDIMODEL shows all configured message types with sender/receiver pairs.

### 5. Test outbound IDoc generation (WE19)

Generate a test IDoc to verify the entire outbound chain works. [src3]

```
Transaction: WE19

1. Enter Basic Type: ORDERS05
2. Click "Create"
3. Fill control record:
   - RCVPRT: LS
   - RCVPRN: EDISUB01
   - SNDPRT: LS
   - SNDPRN: CLNT100
   - MESTYP: ORDERS
4. Fill data segments (E1EDK01, E1EDP01, etc.) with test data
5. Click "Standard Outbound Processing"
6. Note the generated IDoc number
```

**Verify**: `Transaction WE02` --> Search for IDoc number --> Status should be 03 (Data passed to port OK) or 30 (IDoc ready for dispatch).

### 6. Monitor and reprocess failed IDocs (BD87)

Set up monitoring for failed IDocs and establish a reprocessing workflow. [src3]

```
Transaction: BD87

1. Enter selection criteria:
   - Date: today's date range
   - Direction: Inbound / Outbound / Both
   - Status: 51 (not posted), 56 (error), 02 (port error)
2. Execute to display failed IDocs
3. Select IDoc --> Display --> Identify error in status record
4. Fix root cause (master data, authorization, config)
5. Select IDoc --> Process --> Reprocess
```

**Verify**: After reprocessing, IDoc status changes from error (51/56) to success (53 for inbound, 03 for outbound).

## Code Examples

### ABAP: Send outbound IDoc programmatically

```abap
* Input:  Purchase order data to send as ORDERS05 IDoc
* Output: IDoc number and communication status

DATA: ls_control   TYPE edidc,
      lt_data      TYPE STANDARD TABLE OF edidd,
      ls_data      TYPE edidd,
      ls_e1edk01   TYPE e1edk01,
      lv_idoc_num  TYPE edi_docnum.

* Fill control record
ls_control-mestyp = 'ORDERS'.          " Message type
ls_control-idoctp = 'ORDERS05'.        " Basic type
ls_control-rcvprt = 'LS'.              " Receiver partner type
ls_control-rcvprn = 'EDISUB01'.        " Receiver partner number
ls_control-sndprt = 'LS'.              " Sender partner type
ls_control-sndprn = 'CLNT100'.         " Sender partner number

* Fill header segment E1EDK01
ls_e1edk01-belnr = '4500012345'.       " Document number
ls_e1edk01-bsart = 'NB'.              " Document type
ls_data-segnam = 'E1EDK01'.            " Segment name
ls_data-sdata  = ls_e1edk01.           " Segment data
APPEND ls_data TO lt_data.

* Create and dispatch IDoc
CALL FUNCTION 'MASTER_IDOC_DISTRIBUTE'
  EXPORTING
    master_idoc_control = ls_control
  TABLES
    communication_idoc_control = lt_comm_control
    master_idoc_data = lt_data
  EXCEPTIONS
    error_in_idoc_control = 1
    error_writing_idoc_status = 2
    error_in_idoc_data = 3
    OTHERS = 4.

IF sy-subrc = 0.
  COMMIT WORK.
  READ TABLE lt_comm_control INDEX 1 INTO ls_comm.
  lv_idoc_num = ls_comm-docnum.
  WRITE: / 'IDoc created:', lv_idoc_num.
ELSE.
  WRITE: / 'Error creating IDoc:', sy-subrc.
ENDIF.
```

### Python: Process IDoc XML file from SAP file port

```python
# Input:  IDoc XML file exported from SAP file port
# Output: Parsed IDoc data with control record, segments, and status

import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from typing import Optional

@dataclass
class IdocSegment:
    name: str
    data: dict
    children: list = field(default_factory=list)

@dataclass
class IdocDocument:
    idoc_number: str
    message_type: str
    basic_type: str
    sender: str
    receiver: str
    segments: list = field(default_factory=list)

def parse_idoc_xml(file_path: str) -> IdocDocument:
    """Parse SAP IDoc XML file into structured data."""
    tree = ET.parse(file_path)
    root = tree.getroot()

    # Extract control record (EDI_DC40)
    ctrl = root.find('.//EDI_DC40')
    if ctrl is None:
        raise ValueError("No EDI_DC40 control record found")

    doc = IdocDocument(
        idoc_number=ctrl.findtext('DOCNUM', ''),
        message_type=ctrl.findtext('MESTYP', ''),
        basic_type=ctrl.findtext('IDOCTYP', ''),
        sender=ctrl.findtext('SNDPRN', ''),
        receiver=ctrl.findtext('RCVPRN', ''),
    )

    # Parse data segments recursively
    for elem in root.iter():
        if elem.tag.startswith('E1') or elem.tag.startswith('Z1'):
            seg_data = {child.tag: child.text for child in elem
                       if not child.tag.startswith('E1')
                       and not child.tag.startswith('Z1')}
            doc.segments.append(IdocSegment(
                name=elem.tag,
                data=seg_data,
            ))

    return doc

# Example usage
idoc = parse_idoc_xml('/usr/sap/S4H/edi/outbound/ORDERS05_001.xml')
print(f"IDoc {idoc.idoc_number}: {idoc.message_type} "
      f"from {idoc.sender} to {idoc.receiver}")
print(f"Segments: {len(idoc.segments)}")
for seg in idoc.segments[:5]:
    print(f"  {seg.name}: {len(seg.data)} fields")
```

### cURL: Test IDoc HTTP port connectivity

```bash
# Input:  SAP system URL, HTTP port credentials, test IDoc XML
# Output: HTTP response with IDoc posting status

# Test connectivity to SAP IDoc HTTP port
curl -X POST \
  "https://sap-host:8443/sap/bc/srt/idoc?sap-client=100" \
  -H "Content-Type: application/xml" \
  -u "EDIUSER:password" \
  --cert client.pem \
  --key client-key.pem \
  -d @test_idoc.xml \
  -v

# Expected response (success):
# HTTP/1.1 200 OK
# Content-Type: application/xml
# <IDOC_RESPONSE>
#   <DOCNUM>0000000012345678</DOCNUM>
#   <STATUS>64</STATUS>
# </IDOC_RESPONSE>

# Check IDoc status via SAP Gateway (if OData is available)
curl -X GET \
  "https://sap-host:8443/sap/opu/odata/sap/API_IDOC_LOG_SRV/A_IdocStatusRecords?\$filter=IDocNumber eq '0000000012345678'" \
  -H "Accept: application/json" \
  -u "APIUSER:password"
```

## Data Mapping

### IDoc Segment Structure — ORDERS05 [src1, src7]

| Segment | Level | Description | Key Fields | Mandatory |
|---|---|---|---|---|
| E1EDK01 | 1 | Document Header | BELNR (doc number), BSART (doc type), CURCY (currency) | Yes |
| E1EDK14 | 2 | Header Organization | QUESSION (org data qualifier), ORGID (org value) | Yes |
| E1EDK03 | 2 | Header Date | IDDAT (date qualifier), DATUM (date value) | Yes |
| E1EDK04 | 2 | Header Tax | MWSKZ (tax code), MSATZ (tax rate) | No |
| E1EDK05 | 2 | Header Conditions | ALESSION (condition type), BEESSION (condition value) | No |
| E1EDKA1 | 2 | Header Partner | PARVW (partner function: AG=sold-to, WE=ship-to, RE=bill-to) | Yes |
| E1EDP01 | 1 | Line Item | POSEX (item number), MENGE (quantity), MENEE (UoM) | Yes |
| E1EDP02 | 2 | Item Reference | QUESSION (reference qualifier), BESSION (reference number) | No |
| E1EDP19 | 2 | Item Object ID | QUESSION (ID qualifier), IDTNR (material number) | Yes |
| E1EDP20 | 2 | Item Schedule | WMENG (scheduled quantity), EDATU (delivery date) | Yes |

### Data Type Gotchas

- SAP IDoc segments use fixed-width character format (SDATA, 1000 bytes). All fields are CHARACTER type -- numeric values are left-padded with zeros, amounts include sign in last position. Middleware must handle SAP's LSMW-style number formatting. [src1]
- Date fields in IDocs use format YYYYMMDD (8 chars), NOT ISO 8601. Time fields use HHMMSS (6 chars). There is no timezone information in standard IDoc date fields. [src2]
- Material numbers in S/4HANA can be up to 40 characters (MATNR_LONG in new segments) vs. 18 characters in ECC. If integrating with an ECC system, the 40-character material number will be truncated. [src4]
- Currency amounts in IDocs do NOT include decimal separators. The number of decimal places depends on the currency code (e.g., JPY has 0 decimals, USD has 2). Middleware must look up currency decimals from SAP table TCURX. [src1]
- Partner function codes (PARVW) differ between IDoc segments and standard EDIFACT/X12 qualifiers. AG (sold-to) maps to X12 BY, WE (ship-to) maps to X12 ST. The EDI subsystem must maintain a partner function mapping table. [src7]

## Error Handling & Failure Points

### Common IDoc Status Codes [src3]

| Status | Direction | Meaning | Cause | Resolution |
|---|---|---|---|---|
| 02 | Outbound | Error passing data to port | RFC destination down or file path inaccessible | Check SM59 destination; verify file directory permissions |
| 03 | Outbound | Data passed to port OK | Success | No action needed |
| 04 | Outbound | Error in EDI subsystem control info | EDI subsystem rejected the IDoc | Check EDI subsystem logs; verify partner profile |
| 12 | Outbound | Dispatch OK | IDoc successfully transmitted | No action needed |
| 30 | Outbound | IDoc ready for dispatch (ALE) | Waiting for RSEOUT00 to send | Run program RSEOUT00 or transaction WE14 |
| 51 | Inbound | Application document not posted | Business rule violation (missing master data, auth) | Fix master data or authorization; reprocess via BD87 |
| 53 | Inbound | Application document posted | Success | No action needed |
| 56 | Inbound | IDoc with errors added | Syntax or structural error in IDoc data | Fix IDoc data via BD87 edit; reprocess |
| 64 | Inbound | IDoc ready to be transferred to application | Waiting for RBDAPP01 to post | Run BD20 or program RBDAPP01 |
| 66 | Inbound | IDoc waiting for predecessor (serialization) | Predecessor IDoc not yet processed | Process predecessor first; then run BD20 |

### Failure Points in Production

- **Serialization deadlocks (status 66 chain)**: When serialization is enabled, a single failed IDoc blocks ALL subsequent IDocs of the same message type for that partner. Thousands of IDocs can pile up in status 66. Fix: `Use BD87 to identify the blocking IDoc (lowest number in status 51/56), fix and reprocess it, then run BD20 to cascade-process all waiting IDocs.` [src3]
- **Partner profile mismatch on new message types**: Adding a new message type to the EDI subsystem without updating the SAP partner profile causes all IDocs to fail with status 04/56. Fix: `Always update WE20 partner profile BEFORE enabling a new message type in the EDI subsystem; use BD64 to generate partner profiles from the distribution model.` [src6]
- **File port directory permissions**: SAP's sidadm user cannot write to the outbound directory after an OS patch or directory migration. IDocs silently queue in status 30 without errors. Fix: `Check directory permissions with OS-level ls -la; ensure sidadm has read+write; set up monitoring on file port directory for stale files.` [src6]
- **Material number truncation (ECC to S/4HANA)**: S/4HANA's 40-character MATNR_LONG field sends material numbers that ECC's 18-character MATNR field cannot receive, causing inbound posting failures. Fix: `Use IDoc extension with MATNR_LONG mapping or implement a BADI to truncate/map material numbers at the receiving ECC system.` [src4]
- **Change pointer overflow**: Master data distribution via change pointers (BD50/BD52) can generate millions of IDocs after a mass update, overwhelming the system. Fix: `Disable change pointers before mass updates (BD50); use RBDMIDOC in controlled batches; set packet size in RBDMIDOC to 500-1000.` [src5]
- **Duplicate IDoc processing**: Network failures during tRFC transmission can cause the same IDoc to arrive twice. SAP's standard duplicate check only works within the same session. Fix: `Implement custom duplicate detection using IDoc DOCNUM + MESTYP + CREDAT in inbound function module; enable tRFC qRFC for guaranteed exactly-once delivery.` [src3]

## Anti-Patterns

### Wrong: Processing all IDocs immediately with output mode "Transfer IDoc immediately"

```
Partner Profile (WE20) Outbound Parameters:
  Output Mode: Transfer IDoc immediately
  Pack Size: 1
```

This fires a separate RFC call for EVERY single IDoc. For high-volume scenarios (1000+ IDocs/hour), this floods the RFC connection pool and causes timeouts.

### Correct: Use "Collect IDocs" mode with scheduled dispatch

```
Partner Profile (WE20) Outbound Parameters:
  Output Mode: Collect IDocs
  Pack Size: 100

Schedule job RSEOUT00 (transaction WE14) to run every 5-15 minutes.
This batches IDocs and sends them in packets, reducing RFC overhead by 99%.
```

### Wrong: Using WE19 to reprocess production IDocs

```
Transaction WE19 --> Enter failed IDoc number --> Modify data -->
Click "Standard Inbound Processing"
-- This creates a NEW IDoc number, leaving the original in error status.
-- You now have TWO IDocs: one failed, one (maybe) successful.
-- Duplicate processing risk if the original is later reprocessed.
```

### Correct: Use BD87 to edit and reprocess with the SAME IDoc number

```
Transaction BD87 --> Filter for failed IDocs --> Select IDoc -->
Data Record > Display/Change --> Fix the data --> Save --> Reprocess
-- Same IDoc number is retained
-- Status history shows the edit and reprocessing
-- No duplicate risk
```

### Wrong: Hardcoding segment field positions when parsing IDoc flat files

```python
# BAD -- field positions change between IDoc releases and extensions
order_number = line[10:20]  # Assumes BELNR is at position 10-20
```

### Correct: Parse by segment name and field definition from SAP metadata

```python
# GOOD -- use segment definitions from WE60/WE30 export
# Parse XML IDocs instead of flat files when possible
import xml.etree.ElementTree as ET
root = ET.parse('idoc.xml').getroot()
for seg in root.iter('E1EDK01'):
    order_number = seg.findtext('BELNR', '')
```

## Common Pitfalls

- **Not testing with realistic IDoc volumes**: Development systems typically process 10-50 IDocs. Production can process 50,000+ per day. IDoc processing that works in dev can deadlock in production due to database locks on shared tables (EDIDC, EDID4). Fix: `Load-test with production volumes in a QA system; tune RBDAPP01 parallelization settings.` [src5]
- **Ignoring IDoc serialization configuration**: Serialization ensures IDocs are processed in order (e.g., create customer before creating sales order). But misconfigured serialization causes cascading blocks. Fix: `Only enable serialization where business logic requires it; use BD75 to set serialization groups; monitor status 66 IDocs daily.` [src3]
- **Skipping EDI_DC40 control record validation**: The control record contains critical routing information. If MESTYP, IDOCTP, RCVPRN, or SNDPRN are incorrect, the IDoc fails silently or routes to the wrong partner. Fix: `Always validate all control record fields in middleware before sending to SAP; implement a control record template per partner/message type.` [src2]
- **Not handling S/4HANA segment changes**: S/4HANA introduces 37 differences in INVOIC02 alone -- 4 are new functional elements (MATNR_LONG, SGT_RCAT, HANDOVERLOC). Middleware that ignores new segments may lose critical data. Fix: `After every S/4HANA upgrade, re-export IDoc XML schemas (WE60) and compare with middleware mappings.` [src4]
- **Using dialog work processes for mass IDoc processing**: Scheduling mass IDoc reprocessing during business hours consumes dialog work processes, impacting online users. Fix: `Always schedule RBDAPP01 and RSEOUT00 as background jobs; set work process type to BGD in job scheduling.` [src5]
- **Not archiving processed IDocs**: IDoc tables (EDIDC, EDID4, EDIDS) grow unbounded. Systems with 2+ years of IDocs can have 100M+ records, degrading WE02/BD87 performance. Fix: `Implement IDoc archiving using transaction SARA with archiving object IDOC; archive after 90-180 days.` [src5]

## Diagnostic Commands

```
# Check IDoc processing status for today (SAP transaction)
Transaction WE05: Enter date range --> Execute
  Look for: Red/Yellow status indicators

# Count IDocs by status (ABAP report)
Transaction SE16: Table EDIDC
  Selection: CREDAT = today, STATUS = 51 (or 56, 02)
  This gives you the count of failed IDocs by status

# Check partner profile configuration
Transaction WE20: Enter partner number
  Verify: Outbound params (message type, port, basic type)
  Verify: Inbound params (process code, triggering event)

# Verify port connectivity
Transaction WE21: Select port --> Test Outbound Processing
  Success: "IDoc dispatched successfully"
  Failure: Check SM59 for RFC destination status

# Check RFC destination health
Transaction SM59: Select destination --> Connection Test
  Success: Response time < 100ms
  Failure: Check network, credentials, target system status

# Monitor IDoc processing queue
Transaction SMQ1: Check outbound tRFC queue
Transaction SMQ2: Check inbound tRFC queue
  Look for: stuck entries with LUW errors

# Check ALE distribution model
Transaction BD64: Display model --> Verify sender/receiver/message types

# Review IDoc change pointer status
Transaction BD52: Check which message types have change pointers enabled
Transaction RBDMIDOC: Create IDocs from change pointers (batch)

# Verify IDoc archiving status
Transaction SARA: Archiving object IDOC --> Check last run date and record count
```

## Version History & Compatibility

| Release | Date | Status | Key Changes | Migration Notes |
|---|---|---|---|---|
| S/4HANA 2408 | 2024-10 | Current | Incremental segment updates | Check MATNR_LONG support in middleware |
| S/4HANA 2023 | 2023-10 | Supported | E1IDOCENHANCEMENT generic extension | Enable if using key-value custom data |
| S/4HANA 2020 | 2020-10 | Supported | 37 changes in INVOIC02 (4 new functional fields) | Re-export IDoc schemas; update MATNR mapping |
| ECC 6.0 EHP8 | 2016 | Maintenance | Last ECC enhancement package | Plan migration to S/4HANA |
| ECC 6.0 EHP7 | 2014 | EOL | Unicode conversion impact on IDocs | Ensure all IDoc files are UTF-8 |

### Deprecation Policy

SAP maintains backward compatibility for IDoc basic types across releases -- existing basic types are never removed, only extended with new segments. New basic type versions (e.g., ORDERS05 to ORDERS06) are additive. SAP has confirmed IDocs remain a supported integration technology in S/4HANA on-premise and private cloud through at least 2030, though the strategic direction is toward OData and event-based APIs for new development. [src8]

## When to Use / When Not to Use

| Use When | Don't Use When | Use Instead |
|---|---|---|
| EDI with external trading partners (X12/EDIFACT) | S/4HANA Cloud Public Edition (multi-tenant) | OData APIs / SOAP services |
| ALE master data distribution (SAP-to-SAP) | Need synchronous request/response | BAPI/RFC via SM59 |
| High-volume batch document exchange (1000+ docs/day) | Real-time individual record lookup | OData v4 API |
| Existing EDI subsystem integration (Seeburger, OpenText) | New greenfield cloud integration | SAP Event Mesh + Cloud Integration |
| Regulated industries requiring audit trail | Simple master data query | CDS views / OData |
| Complex document structures (nested line items) | Point-to-point API call | REST API with JSON |

## Important Caveats

- S/4HANA Cloud Public Edition does NOT support IDocs or ALE. This is the single most critical constraint to verify before recommending IDoc-based integration. Always confirm the customer's deployment model first. [src8]
- IDoc basic type versions vary between S/4HANA releases. INVOIC02 in S/4HANA 2408 has 4 additional functional fields compared to ECC 6.0. Always verify the exact IDoc schema version using transaction WE60 on the specific system. [src4]
- IDoc processing performance depends heavily on system sizing (number of work processes, database throughput). The same IDoc configuration that handles 1,000 IDocs/hour on a 4-process system may handle 50,000/hour on a 20-process system. Always load-test with production volumes. [src5]
- EDI standard translation (IDoc to X12/EDIFACT and vice versa) is NOT built into SAP. An external EDI subsystem or SAP Integration Suite is required. The IDoc framework only handles the SAP side of the exchange. [src6]
- IDoc status records grow linearly with processing events. A single IDoc can accumulate 20+ status records over its lifecycle. In high-volume systems, the EDIDS table can become the largest table in the system. Archiving is essential. [src3]

## Related Units
<!-- Generated from related_kos frontmatter -->

- [SAP S/4HANA OData API](/business/erp-integration/sap-s4hana-odata-api/2026) -- Synchronous REST alternative to IDocs
- [SAP S/4HANA Cloud API](/business/erp-integration/sap-s4hana-cloud-api/2026) -- For public cloud edition (no IDoc support)
- [SAP BAPI/RFC Integration](/business/erp-integration/sap-bapi-rfc-integration/2026) -- Synchronous function calls vs asynchronous IDocs
